-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEuler30(Java)
83 lines (63 loc) · 1.99 KB
/
Euler30(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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*This is a solution to the Euler problem #30 which seeks a solution to the following:
*Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.
*This solution was again created in Java.
*/
public class Euler30 {
public static void main(String[] args) {
int num[] = new int [5];
int numCompare[] = new int [10];
int sum = 0;
int realSum = 0;
boolean test;
String number;
for (int i = 2; i < 350000; i++) {
number = Integer.toString(i);
num = toArray(number);
sum = Power5(num);
numCompare = ArrayTime(sum);
test = Compare (num, numCompare);
if (test == true) {
realSum+=sum;
System.out.println(sum);
}
}
System.out.println(realSum);
}
public static int[] toArray (String x) { //takes each number starting from 2 and parses it into
int num[] = new int [10]; // an array. for example the number 132 would be
String dig; // turned into an array [1][3][2].
for (int i = x.length(); i >0; i--) { //This makes accessing it's individual elements
dig = x.substring(i-1,i);
//System.out.println(dig);
num[x.length()-i] = Integer.parseInt(dig);
}
return num;
}
public static int Power5 (int x[]) { //takes the num array created and gives the sum of
//the 5th power of each digit in the number array.
int sum = 0;
for (int i = 0; i < 6; i++) {
sum += x[i]*x[i]*x[i]*x[i]*x[i];
}
return sum;
}
public static int[] ArrayTime (int x) { //takes the sum and turns it into an array as well
int num[] = new int [10];
String dig, sub;
dig = Integer.toString(x);
for (int i = dig.length(); i >0; i--) {
sub = dig.substring(i-1,i);
num[dig.length()-i] = Integer.parseInt(sub);
}
return num;
}
public static boolean Compare (int x[], int y[]) { //compares the arrays to check for equality
boolean test = true;
for (int i = 0; i < 7; i++) {
if (x[i] != y[i]) {
test = false;
}
}
return test;
}
}