forked from karan/Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHappyNumber.java
54 lines (42 loc) · 859 Bytes
/
HappyNumber.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
44
45
46
47
48
49
50
51
52
53
54
import java.util.ArrayList;
/**
* This program calculates the first 8 happy numbers starting from a given
* number.
*
* Happy Number: http://en.wikipedia.org/wiki/Happy_number
*
* @author manojreddy
*
*/
public class HappyNumber {
public static boolean isHappy(int x){
ArrayList<Integer> history = new ArrayList<Integer>();
while(x!=1){
history.add(x);
int sum = 0;
while(x!=0){
sum+= Math.pow(x%10,2);
x/=10;
}
x = sum;
if(history.contains(x)){
return false;
}
}
return true;
}
//Assuming that "start" is a positive integer
public static void print8HappyNumbers(int start){
int found = 0;
while(found < 8){
if(isHappy(start)){
System.out.println(start);
found++;
}
start++;
}
}
public static void main(String[] args) {
print8HappyNumbers(100);
}
}