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
1
The given code 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);
}
}
- 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
Geography,
1 month ago
Math,
2 months ago
Science,
10 months ago
Social Sciences,
10 months ago
Math,
10 months ago