Write a program to check whether a given number is an ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
For example, 6, 8 are ugly while 14 is not ugly since it includes another prime factor 7.
Note that 1 is typically treated as an ugly number.
ugly num是因数只为2,3,5的数。1是特别的丑数。
public boolean isUgly(int num) {
if (num<=0) return false;
while(num%2==0) num = num/2;
while(num%3==0) num = num/3;
while(num%5==0) num = num/5;
if(num==1) return true;
return false;
}
难点在于循环的判断条件。一个数可以被i整除,就是num%n==0,余数为0;
Write an algorithm to determine if a number is “happy”.
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
快乐数则是每一位的平方相加得到一个数,继续这个数每一位平方相加,直到最后相加为1;
这里分享一个归纳思考过程:
显然一个数如果进行了几次运算后为1了就会一直为1,收敛与1,是快乐数。
那如何证明n不是快乐数?
那就是操作构成了循环!!
一个数n有8位,位数记作l,那么最大就是9999 9999 ,那么n进行一次上述过程,得到的是81 * 8 = 648;
很显然648 < 100 * l = 800;
可以看出做个操作对大数进行了很大的缩小;
对不同位数的数进行操作:
7位数 < 700;
6位数 < 600 ;
5位数 < 500;
4位数 < 400 ;
3位数 < 300 ;
2位数 < 200 ;
1位数 < 100;
需要注意的是,从2位数开始,进行一次操作可能会放大这个数,比如99 》》 162,但是也有相当一部分数会变小;
1位数也是如此;
但是就算n是2位数或者1位数,而且还会变大的,顶多变成3位数呗,3位数又会继续变小。而三位数进行一次操作结果会在[1,300]里面分布,所以就算最差的情况,对一个三位数进行301次操作总,最后得出来的数肯定有一个与前三百个相同,从而开始以300为周期的循环,也就证明n不是快乐数。
解决这个问题的关键就是这个运算要进行多少次?即循环的判断条件是什么?
可以利用Hashset的性质:
..算了我去翻书了,争取写一个学习总结
不是快乐数的数称为不快乐数(unhappy number),所有不快乐数的数位平方和计算,最後都会进入 4 → 16 → 37 → 58 →
89 → 145 → 42 → 20 → 4 的循环中。
本文介绍了一种检查给定数字是否为丑数的方法,丑数是指仅包含质因数2、3、5的正整数。同时,还探讨了判断一个数是否为快乐数的算法,快乐数是通过迭代其各位数字的平方和最终能收敛到1的正整数。

3404

被折叠的 条评论
为什么被折叠?



