- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
Latest commit
70 lines (61 loc) · 1.84 KB
/
Copy pathMain.java
File metadata and controls
70 lines (61 loc) · 1.84 KB
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
importjava.util.ArrayList;
importjava.util.List;
/*
@author: mc-es
Problem 50
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13.
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?
Answer: 997651
*/
publicclassMain {
publicstaticvoidmain(String[] args) {
intlimit = 1000000;
int[] result = findLargestPrimeSum(limit);
System.out
.println("The largest prime number under " + limit + ": " + result[0] + ", sequence length: " + result[1]);
}
privatestaticbooleanisPrime(intn) {
if (n < 2) {
returnfalse;
}
for (inti = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
returnfalse;
}
}
returntrue;
}
privatestaticList<Integer> generatePrimes(intlimit) {
List<Integer> primes = newArrayList<>();
for (inti = 2; i < limit; i++) {
if (isPrime(i)) {
primes.add(i);
}
}
returnprimes;
}
privatestaticint[] findLargestPrimeSum(intlimit) {
List<Integer> primes = generatePrimes(limit);
intmaxLength = 0;
intmaxPrime = 0;
for (inti = 0; i < primes.size(); i++) {
for (intj = i + maxLength; j < primes.size(); j++) {
inttotal = 0;
for (intk = i; k < j; k++) {
total += primes.get(k);
}
if (total > limit) {
break;
}
if (primes.contains(total)) {
maxLength = j - i;
maxPrime = total;
}
}
}
returnnewint[] { maxPrime, maxLength };
}
}