Answer to Question #249158 in Java | JSP | JSF for ranju

Question #249158

.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


1
Expert's answer
2021-10-10T01:49:03-0400
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));  
    }  
}  

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS