Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ================================
- chapter 4: Loops
- Ex17: Happy number
- ================================
- */
- public class MyProgram {
- public static void main(String[] args) {
- //variables
- final int SIZE=3;
- int count=0; //count consecutive happy number
- int number=0; //var to save the last happy number (to use outside the loop)
- boolean isHappy;
- //loop until fount 3 consecutive happy numbers
- for(int i=10,index=0;count<SIZE;i++){
- isHappy= checkNumber(i);
- //if the number is happy inc count, inc index, print msg
- if (isHappy) {
- count += 1;
- index+=1; //index represent the how many happy numbers found
- System.out.println(index+") "+i+" is a happy number :-)");
- number=i; //save the number i to use outside the loop
- }
- else
- count=0; //reset count
- }
- System.out.printf("%d %d %d",number-2,number-1,number); //print 3 consecutive happy numbers
- }
- //function sum the digits's power
- public static int sumPow(int number){
- //variables
- int sum=0; //represent the sum of digit's power
- int base; //represent single digit
- final int EXPONENT=2;
- //loop until no digits left
- while(number>0){
- base=number%10; //get single digit
- sum+=Math.pow(base,EXPONENT); //sum the power
- number/=10; //get rid of last digit
- }
- return sum;
- }
- //function checks if the number is happy
- public static boolean checkNumber(int number){
- int sum=0;
- //loop until 1 digit number left
- do {
- sum = sumPow(number); //getting the sum of power digits
- number=sum; // update the new number to send
- }while(sum>9);
- if (sum!=1)
- return false; //not happy → false
- return true; //happy number → true
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment