A prime number is a number that cannot be divided by any number other than 1 and itself (ie. 2, 17, 53, etc.).Find the sum of all prime numbers from 0 to 7600 (2 + 3 + 5 + 7 + 11 + 13... = ?).
These are two possible solutions in Java.
SOLUTION #1
public static void main(String[] args) {
int max = 7600, sum = 0;
ArrayList<Integer> primes = new ArrayList<Integer>();
for(int i = 2; i <= max; i++) {
boolean prime = true;
for(int j = 0; j < primes.size() && prime; j++) {
if(i % primes.get(j) == 0)
prime = false;
if(primes.get(j) > i/2)
j=primes.size();
}
if(prime) {
primes.add(i);
sum += i;
}
}
System.out.println("Sum:\t" + sum);
}
SOLUTION #2
public static ArrayList<Integer> primes = new ArrayList<Integer>();
public static boolean isPrime(int k) {
boolean prime = true;
for(int idx = 0; idx < primes.size() && prime; idx++) {
if(k % primes.get(idx) == 0)
prime = false;
if(primes.get(idx) > k/2)
idx = primes.size();
}
if(prime) primes.add(k);
return prime;
}
public static void main(String[] args) {
int max = 7600, sum = 0;
for(int i = 2; i <= max; i++) {
if(isPrime(i))
sum += i;
}
System.out.println("Sum:\t" + sum);
}