`

Google Interview - Happy Number

 
阅读更多

happy number is 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, while those that do not end in 1 are unhappy numbers. Display an example of your output here.

 

If n is not happy, then its sequence does not go to 1. Instead, it ends in the cycle:

4, 16, 37, 58, 89, 145, 42, 20, 4, ...

To see this fact, first note that if n has m digits, then the sum of the squares of its digits is at most 9^2 m, or 81m.

For m=4 and above,

n\geq10^{m-1}>81m

so any number over 1000 gets smaller under this process and in particular becomes a number with strictly fewer digits. Once we are under 1000, the number for which the sum of squares of digits is largest is 999, and the result is 3 times 81, that is, 243.

  • In the range 100 to 243, the number 199 produces the largest next value, of 163.
  • In the range 100 to 163, the number 159 produces the largest next value, of 107.
  • In the range 100 to 107, the number 107 produces the largest next value, of 50.

Considering more precisely the intervals [244,999], [164,243], [108,163] and [100,107], we see that every number above 99 gets strictly smaller under this process. Thus, no matter what number we start with, we eventually drop below 100. An exhaustive search then shows that every number in the interval [1,99] either is happy or goes to the above cycle.

The above work produces the interesting result that no positive integer other than 1 is the sum of the squares of its own digits, since any such number would be a fixed point of the described process.

public class HappyNumber{
   public static boolean isHappyNumber(long number){
       long m = 0;
       int digit = 0;
       Set<Long> cycle = new HashSet<Long>();
       while(number != 1 && cycle.add(number)){
           m = 0;
           while(number > 0){
               digit = (int)(number % 10);
               m += digit*digit;
               number /= 10;
           }
           number = m;
       }
       return number == 1;
   }
 
   public static void main(String[] args){
       for(long num = 1,count = 0;count<8;num++){
           if(happy(num)){
               System.out.println(num);
               count++;
           }
       }
   }
}

 

Reference:

http://en.wikipedia.org/wiki/Happy_number

http://rosettacode.org/wiki/Happy_numbers#Java

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics