计算素数之和 [英] Calculate the sum of prime numbers

查看:292
本文介绍了计算素数之和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算素数之和?我检索它们的代码如下

How can I calculate the sum of prime numbers? My code to retrieve them is below

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);
      }
    }
  }
}

推荐答案

您的算法将非常慢.我会考虑使用Euler的筛子(维基百科已在Eratosthenes的筛子中将其列出.)

要在代码中保留素数之和,只需在循环外添加一个变量,并在每次i == j时向其添加i.对于数学解决方案,请尝试以下操作:

Prime Sums-来自Wolfram MathWorld [
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[^]


请提出一个实际问题;否则,我们将无法为您解答.
Please ask an actual question; otherwise, we won''t be able to answer you.


请先正确指定您的问题...
接下来,改进素数算法.因为效率很高.
您无需将第一个循环从i = 1迭代到num.
我该死的确保从i = 1到sqrt(num)的循环就足够了.
-Satyam
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


这篇关于计算素数之和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆