Computer Science, asked by deon3339, 2 months ago

Write a Java program that accepts two numbers from the user and calculates the sum
of all prime numbers between the given numbers.

Answers

Answered by anindyaadhikari13
1

\texttt{\textsf{\large{\underline{Solution}:}}}

The given co‎‎de is written in Java.

import java.util.*;

public class PrimeSum{

   static boolean isPrime(int n){

       int c=0;

       for(int i=1;i<=n;i++){

           if(n%i==0)

               ++c;

       }

       return c==2;

   }

   public static void main(){

       Scanner _=new Scanner(System.in);

       int a,b,i,sum=0;

       System.out.print("Enter first number: ");

       a=_.nextInt();

       System.out.print("Enter second number: ");

       b=_.nextInt();

       _.close();

       for(i=a;i<=b;i++){

           if(isPrime(i))

               sum+=i;

       }

       System.out.println("The sum of all prime numbers in this range is: "+sum);

   }

}

\texttt{\textsf{\large{\underline{Explanation}:}}}

  • isPrime() checks whether a number is Prime or not.
  • The numbers are taken as input.
  • Sum is initialised to 0.
  • Then a loop iterates in the entered range.
  • If the numbers in the range is prime, it is added to sum.
  • At last, the sum is displayed.

See the attachment for output.

Attachments:
Similar questions