-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHappyNumberBetween1ToN.java
43 lines (43 loc) · 1.22 KB
/
HappyNumberBetween1ToN.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// WAP to define a method to print happy number between 1 to N.
//A number is called happy if it leads to 1 after a sequence of steps where in each
//step number is replaced by sum of squares of its digit that is if we start with
//Happy Number and keep replacing it with digits square sum, we reach 1.
//EX : Input: n = 19 Output: True 19 is Happy Number,1^2 + 9^2 = 82,8^2 + 2^2 = 68
//6^2 + 8^2 = 100,1^2 + 0^2 + 0^2 = 1 As we reached to 1, 19 is a Happy Number.
// 1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68
import java.util.Scanner;
public class HappyNumberBetween1ToN{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Number upto which Happy Number you want : ");
int n = sc.nextInt();
System.out.println("The Happy Number is : ");
boolean j;
int i=1;
while(i<=n)
{
j = isHappyNumber(i);
if(j==true)
System.out.print(i+" ");
i++;
}
}
public static boolean isHappyNumber(int n)
{
while(n>9)
{
int sum=0;
while(n!=0)
{
int rem = n%10;
sum = sum +(rem*rem);
n = n/10;
}
n = sum;
}
if(n==1||n==7)
return true;
else
return false;
}
}