Answer:
Step-by-step explanation:
The following code is written in Java and creates the necessary code so that two int inputs are read and looped through all the numbers between them to find all the primes. These primes are counted and summed. Finally, printing out the sum and the number of primes found to the console.
import java.util.ArrayList;
import java.util.Scanner;
class SumPrimes{
public static void main(final String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> primes = new ArrayList<>();
int num1, num2, numPrime = 0;
System.out.println("Enter number 1:");
num1 = in.nextInt();
System.out.println("Enter number 2:");
num2 = in.nextInt();
for (int x = num1; x <= num2; x++) {
if (isPrime(x) == true) {
primes.add(x);
numPrime += 1;
}
}
System.out.println("There are " + numPrime + " primes in the array.");
System.out.println("Their sum is " + sumArray(primes));
}
public static int sumArray(ArrayList<Integer> arr) {
int sum = 0;
for (int x: arr) {
sum += x;
}
return sum;
}
static boolean isPrime(int n) {
if (n <= 1)
return false;
for (int i = 2; i < n; i++)
if (n % i == 0)
return false;
return true;
}
}