hpilo

Chapter4_Loops_Ex17

Dec 15th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1. /*
  2.     ================================
  3.             chapter 4: Loops
  4.  
  5.             Ex17: Happy number
  6.     ================================
  7. */
  8.  
  9.  
  10. public class MyProgram {
  11.     public static void main(String[] args) {
  12.  
  13.         //variables
  14.         final int SIZE=3;
  15.         int count=0;    //count consecutive happy number
  16.         int number=0;  //var to save the last happy number (to use outside the loop)
  17.         boolean isHappy;
  18.  
  19.         //loop until fount 3 consecutive happy numbers
  20.         for(int i=10,index=0;count<SIZE;i++){
  21.  
  22.            isHappy= checkNumber(i);
  23.  
  24.            //if the number is happy inc count, inc index, print msg
  25.            if (isHappy) {
  26.                count += 1;
  27.                index+=1;    //index represent the how many happy numbers found
  28.                System.out.println(index+") "+i+" is a happy number :-)");
  29.                number=i;    //save the number i to use outside the loop
  30.            }
  31.            else
  32.                count=0; //reset count
  33.         }
  34.  
  35.         System.out.printf("%d %d %d",number-2,number-1,number); //print 3 consecutive happy numbers
  36.     }
  37.  
  38.     //function sum the digits's power
  39.     public static int sumPow(int number){
  40.  
  41.         //variables
  42.         int sum=0;  //represent the sum of digit's power
  43.         int base;  //represent single digit
  44.         final int EXPONENT=2;
  45.  
  46.         //loop until no digits left
  47.         while(number>0){
  48.  
  49.             base=number%10; //get single digit
  50.             sum+=Math.pow(base,EXPONENT);   //sum the power
  51.             number/=10; //get rid of last digit
  52.         }
  53.  
  54.         return sum;
  55.     }
  56.  
  57.     //function checks if the number is happy
  58.     public static boolean checkNumber(int number){
  59.  
  60.         int sum=0;
  61.  
  62.         //loop until 1 digit number left
  63.         do {
  64.             sum = sumPow(number);  //getting the sum of power digits
  65.             number=sum; // update the new number to send
  66.  
  67.         }while(sum>9);
  68.  
  69.  
  70.         if (sum!=1)
  71.             return false;   //not happy → false
  72.         return true;    //happy number → true
  73.     }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment