.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. using java
import java.util.Scanner;
public class Main
{
static boolean is_prime(int n) {
if(n == 1)
return false;
for (int i = 2; i*i <= n; i++)
{
if (n % i == 0)
return false;
}
return true;
}
static int sumPrime(int m, int n)
{
int sum_prime = 0;
for (int i = n; i >= m; i--){
boolean p = is_prime(i);
if (p)
{
System.out.println(i);
sum_prime = sum_prime + i;
}
}
return sum_prime;
}
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
System.out.println("Enter m: ");
int m=in.nextInt();
System.out.println("Enter n: ");
int n=in.nextInt();
System.out.println("The prime numbers are: ");
System.out.println("The sum is: " +sumPrime(m, n));
}
}
Comments
Leave a comment