Click here to Skip to main content
15,889,034 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I calculate the sum of prime numbers? My code to retrieve them is below
C#
import java.io.*;
class PrimeNumber {
  public static void main(String[] args) throws Exception{
    int i ;
    BufferedReader bf = new BufferedReader(
              new InputStreamReader(System.in));
    System.out.println("Enter number:");
    int num = Integer.parseInt(bf.readLine());
  
    System.out.println("Prime number: ");
    for (i=1; i < num; i++ ){
      int j;
      for (j=2; j<i; j++){
        int n = i%j;
        if (n==0){
          break;
        }
      }
      if(i == j){
        System.out.print("  "+i);
      }
    }
  }
}
Posted
Updated 20-Jan-10 20:47pm
v3

Your algorithm is going to be extremely slow. I would look into using Euler's Sieve (Wikipedia has listed it in the Sieve of Eratosthenes.)

To keep the sum of a prime number in your code, just have a variable outside the loops and add i to it every time i == j. For a mathematical solution, try this:

Prime Sums -- from Wolfram MathWorld[^]
 
Share this answer
 
Please ask an actual question; otherwise, we won't be able to answer you.
 
Share this answer
 
please specify your problem properly first...
next, improve the algorithm for prime no. coz it's quite efficient.
you don't need to iterate the first loop from i = 1 to num.
I'm damn sure that the loop from i = 1 to sqrt(num) will be enough.
-Satyam
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900