Happy Number
Problem to find the happy number or not.
Happy number is square the each and every digit and sum the squared value and continue the same process until length become one.If length value is "1" that is happy number.
Example-1:
Input : n = 91 Output : Happy Number Explain : 92+12=82 82+22=68 62+82=100 12+02+02=1. It's happy number.
Example-2:
Input : n=37 Output : Happy number Explain : 32+72=58 52+82=89 82+92=145 12+42+52=42 42+22=20 22+02=4. It's Not a Happy number.
Solution
public class Main { public static void main(String [] args) { int n = 91; int sum = 0; do { sum = 0; while(n != 0) { sum = sum + (int)Math.pow(n%10,2); n = n/10; } n = sum; }while(sum >= 10); if(sum == 1) { System.out.print("Happy Number"); } else { System.out.print("Not a Happy Number"); } } }
n = 91 n = str(n) while(len(n) != 1): k = 0 for x in n: k += int(x)**2 n = str(k) if(n == "1"): print("Happy number") else: print("Not a Happy number")
Output
Happy Number