-
Notifications
You must be signed in to change notification settings - Fork 0
/
Euler12(Java)
116 lines (101 loc) · 2.29 KB
/
Euler12(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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
/*This is my solution to Problem #12 which asks:
*What is the value of the first triangle number to have over five hundred divisors?
*This program was made in Java.
*/
public class Euler12 {
public static void main(String args[]){
long startTime = System.currentTimeMillis();
int freq[]= new int [10000];
long triNum = 3;
int factors[] = {};
long temp = 1;
factors = getPrimes();
for (long i = 3; i < 99999; i++)
{
triNum+=i;
temp = triNum;
System.out.println(); //helps with readability of output
System.out.print(triNum + " ");
for (int j = 0; j<factors.length; j++)
{
if (temp > factors[j] && factors[j] < 1000000)
{
while (temp%factors[j]==0)
{
temp = temp/factors[j]; //runs through each prime factor
freq[j]++;
//System.out.print(" " + factors[j] + " ");
//System.out.print(" " + freq[j] + " ");
if (temp == 1 || temp < factors[j])
{
temp = triNum;
break;
}
}
temp = triNum;
//System.out.println(temp);
}
else
{
break;
}
//System.out.print(freq[j] + " ");
}
Euler12.DivFunction(freq);
System.out.print(Euler12.DivFunction(freq));
if (Euler12.DivFunction(freq)>=500)
{
break;
}
freq = WipeFreq();
}
}
public static int[] WipeFreq() //resets the divisor frequency count
{
int freq[] = new int[10000];
return freq;
}
public static int DivFunction(int x[]) //calculates the number of divisors of each number
{
int div = 1;
for (int j = 0; j < x.length; j++)
{
if (x[j] != 0)
{
//System.out.print(" " + x[0] + "\t");
div*=x[j]+1;
//System.out.println(div);
}
if (div >=500) //stops when 500+ are found
{
break;
}
}
//System.out.print(" " + div + " ");
return div;
}
public static int[] getPrimes() //sieve to retrieve the prime numbers
{
int factors[] = new int [2000000];
int base = 0;
int sqrt = 1414;
boolean[] Composite = new boolean[2000000+1];
for (int m = 2; m <= sqrt; m++)
{
if (!Composite[m])
{
factors[base]=m;
base++;
for (int k = m * m; k <= 2000000; k +=m)
Composite[k] = true;
}
}
for (int m = sqrt; m <= 2000000; m++)
if (!Composite[m])
{
factors[base]=m;
base++;
}
return factors;
}
}