.Write a program to find the sum of all the prime numbers in the range n to m. Display each prime number and the final sum.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyBoard = new Scanner(System.in);
int n=0;
while(n<=1) {
System.out.print("Enter n>1: ");
n = keyBoard.nextInt();
}
int m=0;
while(m<=n) {
System.out.print("Enter m>n: ");
m = keyBoard.nextInt();
}
int sum = 0;
for (int number = n; number <= m; number++) {
boolean is_Prime = true;
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
is_Prime = false;
break;
}
}
if (is_Prime) {
System.out.print(number + " ");
sum += number;
}
}
System.out.println("\nThe sum of all the prime numbers: " + sum);
keyBoard.close();
}
}
Comments
Leave a comment