Saturday 13 February 2016

JAVA: Happy Number

Problem: Happy Number

Let the sum of the square of the digits of a positive integer S0 be represented by S1. In a similar way, let the sum of the squares of the digits of S1 be represented by S2 and so on. If Si = 1 for some i ³ 1, then the original integer S0 is said to be Happy number. A number, which is not happy, is called Unhappy number.
For example, 
7 is a Happy number since 7 -> 49 -> 97 -> 130 -> 10 -> 1 and 
4 is an Unhappy number since 4 -> 16 -> 37 -> 58 -> 89 -> 145 -> 42 -> 20 -> 4.

Solve:

7 is Happy number-why? cause-

72 = 49
42 + 92 = 16 + 81 = 97
92 + 72 = 81 + 49 = 130
12 + 32 + 02 = 1+9+0 = 10
12 + 02 = 1

4 is Unhappy number because it never return to 0

Lets see the following code:
// ADLabs

import java.util.HashSet;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Set;


public class HappyNumber {

 // used to tell if a number has already been checked
 ArrayList checked = new ArrayList(); 
 
 public static void main(String[] args) {
  
  HappyNumber hn = new HappyNumber();
  Scanner sc =new Scanner(System.in);
  
  System.out.println("Happy Number Checker (to Stop enter 0)");
  System.out.print("Enter Number : ");
  
  int number = sc.nextInt();
  //System.out.print(hn.sum_sq_digits(number));
  //
  
  while (number>0) {
   
   if (hn.isHappy(number)) {
   System.out.println(number + " is Happy Number :)");
   }else {
   System.out.println(number + " is UnHappy Number :(");
   }
   System.out.print("Enter Number : ");
   number = sc.nextInt();
  }
  //
  sc.close();
 }

 
 public boolean isHappy(int i) {
    
  Set check = new HashSet();
  
  while (check.add(i)) //add and check database and return true
        {
            
            i = sum_sq_digits(i); //return sum of 2 
            System.out.print(i +" ");
            if (i==1)
             break; 
        }
  System.out.println("");
        
  
  return i==1; // if i=1 return true
  
 } 
 
 public int sum_sq_digits(int number){
  
  int sum = 0;
        while (number > 0)
        {
         sum += Math.pow(number % 10, 2);
            number /= 10;
        }
        return sum;
 }
 
}





Console:



Console Output
Console Output