i have the following code, but the answer is coming out to be 2.
public class Main {
public static void main(String[] args) {
int sum = 0;
int count = 0;
for(int i = 2; i <= 50; i ) {
for(int j = 1; j <= i; j ) {
System.out.println(j);
if(i % j == 0) {
count ;
}
if(count == 2) {
System.out.println(i);
sum = sum i;
}
}
}
System.out.println("The sum: " sum);
}
}
CodePudding user response:
You were close. But here is all you need.
- first, set sum to 2. It is the only even prime and doing this allows a better increment below
- now increment the test cases starting at 3 and incrementing by 2. Skip even values.
- now divide by each test case by numbers from 2 to the
sqrt(i)
. No need to go beyond that. - as soon as you have a successful division, end the inner loop and start the next of the outer loop.
- otherwise, if the inner loop completes, add
i
to sum.
int sum = 2;
outer:
for(int i = 3; i <= 50; i = 2) {
for(int j = 2; j <= Math.sqrt(i); j ) {
if(i % j == 0) {
continue outer;
}
}
sum = i;
}
System.out.println("The sum: " sum);
An improvement would be to store the primes as they are found and then only divide by those instead of arbitrary numbers.
CodePudding user response:
Disclaimer: this code was written by Github Copilot with minimal supervision.
class Scratch {
// find the sum of all prime numbers between 2 and n
public static int sumPrimes(int n) {
int sum = 0;
for (int i = 2; i < n; i ) {
if (isPrime(i)) {
sum = i;
}
}
return sum;
}
// return true if n is prime
public static boolean isPrime(int n) {
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i * i <= n; i = 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// print sum of primes between 2 and 50
System.out.println("The sum: " sumPrimes(50));
}
}
Prints:
The sum: 328
CodePudding user response:
Maybe a minimal version with recursive method based on Aivean response:
class Scratch {
// find the sum of all prime numbers between 2 and n
public static int sumPrimes(int n) {
if (n >= 2) {
return (isPrime(n) ? n : 0) sumPrimes(n-1);
}
return 0;
}
// return true if n is prime
public static boolean isPrime(int n) {
for (int i = 2; i < n; i ) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// print sum of primes between 2 and 50
System.out.println("The sum: " sumPrimes(50));
}
}