-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsecutivePrimeSums.java
94 lines (72 loc) · 2.42 KB
/
ConsecutivePrimeSums.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
package tenprojecteulersolutionsinjava;
import java.util.Scanner;
public class ConsecutivePrimeSums
{
public static void main(String[] args)
{
final int NUMS_PER_LINE = 12; // Display 12 Numbers before indenting to next line
int count = 0; // Count the number of prime numbers
int number = 2; // A number to be tested for primeness
int squareRoot = 1; // To check whether number less than or equal to squareRoot
Scanner inputN = new Scanner(System.in);
System.out.print("Find all prime numbers <= n, enter n: ");
int n = inputN.nextInt();
// A list to hold prime numbers
java.util.List<Integer> primeList =
new java.util.ArrayList<Integer>();
System.out.println("The prime numbers are: \n");
// Repeatedly find prime numbers
while (number <= n)
{
// Assume the number is prime
boolean isPrime = true; // Is the current number prime?
if (squareRoot * squareRoot < number) squareRoot++;
// ClosestPair if number is prime
for (int i = 0; i < primeList.size()
&& primeList.get(i) <= squareRoot; i++)
{
if (number % primeList.get(i) == 0)
{ // If true, not prime
isPrime = false; // Set isPrime to false
break; // Exit the for loop
}
} // close for
// Print the prime number and increase the count
if (isPrime)
{
count++; // Increase the count
primeList.add(number); // Add a new prime to the list
if (count % NUMS_PER_LINE == 0)
{
// Print the number and advance to the new line
System.out.println(number);
}
else
System.out.print(number + " ");
} // close outer if
// Check if the next number is prime
number++;
} // close while
System.out.println("\n" + count +
" prime(s) less than or equal to " + n);
int sum = 0;
int currentPrime;
java.util.List<Integer> sumPrimes =
new java.util.ArrayList<Integer>();
for (int i = 2; i < primeList.size(); i++)
{
currentPrime = primeList.get(i);
sum = sum + currentPrime;
boolean prime = true;
if (sum % 2 == 0)
{
prime = false;
break;
}
if (prime == true)
{
sumPrimes.add(sum);
}
} // close for loop
} // close main()
}