niithub

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

译文:

10以下的素数之和为17,求出2000000以下的素数之和。

=======================

第一次code:

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) 
 5     {
 6         Scanner input = new Scanner(System.in);
 7         long start = System.currentTimeMillis();
 8         System.out.println(su(2000000));
 9         long end = System.currentTimeMillis();
10         System.out.println(end-start);
11     }
12     /*
13    *  判断是否为素数
14    * /
15     static boolean sum(int n)
16     {
17         boolean isPrime=true;
18         int s=(int)Math.sqrt(n);
19         for(int i=s;i>1;i--)
20         {
21             if(n%i==0)
22             {
23                 isPrime=false;
24             }
25         }
26         return isPrime;
27     }
28     /*
29    *  循环遍历素数
30    *  求和
31    */
32     static long su(int n)
33     {
34         long sum=0;
35         for(int i=2;i<n;i++)
36         {
37             if(sum(i)== true)
38             {
39                 sum += i;
40             }
41         }
42         return sum;
43     }
44 }

结果为142813828922,时间效率为8257毫秒。

posted on 2016-09-04 22:09  niithub  阅读(152)  评论(0编辑  收藏  举报