We think that 2 is the first prime, 3 is the second prime, 5 is the third prime, and so on.
Now, two integers n and m are given, 0<n<=m<=200. The program is to calculate the sum of n-th to m-th primes, including the n-th and the m-th prime.
Pay attention that it is to calculate the sum of n-th to m-th primes, but not the primes between n and m.
The program is following.
//Sum of Primes
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt(), m = in.nextInt(), count = 0, number = 2, sum = 0;
while (count < m)
{
boolean IsPrime = true;
for (int i=2;i<number;i++)
{
if (number%i==0)
{
IsPrime = false;
break;
}
}
if (IsPrime)
{
count++;
if (count>=n)
sum += number;
}
number++;
}
System.out.println(sum);
}
}
No comments:
Post a Comment