2013-10-05 20 views
-2

嗨,我在使用java时遇到了一些麻烦,并让它显示前200个素数。 我现在拥有的是一个有200个数字限制的代码,它会从200个数字中选择素数。 但是如果我想精确显示200个素数呢?显示Java中的前200个素数

我有一个代码,它有2个方法。第一种方法专注于显示数字,第二种方法专注于确定数字是否为素数。 如果它是真的,它将返回到方法1.

所以我想要做的是在for循环中做一个计数器和一个while循环。 只有它导致只给了一定的数字200次,所以我使用评论//来阻止while代码。

public static void main (String[] args) 
{ 

    int limit = 200; 
    for (int getal =2; getal<=limit; getal++) 
    { 
    //int count = 0; 
    //while (count < 201) 

     if (Priem(getal)) 
     { 
      //count++; 
      System.out.println(getal); 
     } 
    } 

} 

public static boolean Priem (int getal) 
{ 

    for (int i=2; i<getal; i++) 
    { 

     if (getal%i == 0) 
     { 
     return false; 
     } 

    } 
    return true; 
} 

任何人有任何想法如何拉这个关闭?谢谢您的帮助!

+0

作业....... –

+0

您的代码当前查看所有数字最多200,并检查它们是否为总数。 –

+0

请使用[Java命名约定](http://www.oracle.com/technetwork/java/codeconv-138413.html)。从公认的标准中脱离出来会让你更难以阅读。例如,方法名称应该是小写。 –

回答

2

试试这个:

public static void main (String[] args) 
{ 

int countofPrime = 0; 
for (int getal =2; ; getal++) 
{ 
//int count = 0; 
//while (count < 201) 

    if (Priem(getal)) 
    { 
     countofPrime++; 
     System.out.println(getal); 
     if(countofPrime == 200) 
      break; 
    } 
} 

} 

public static boolean Priem (int getal) 
{ 

for (int i=2; i<getal; i++) 
{ 

    if (getal%i == 0) 
    { 
    return false; 
    } 

} 
return true; 
} 
+0

很酷的感谢解决方案!完美的作品! 我不知道你可以打破for循环的条件,感谢您的快速回复! – SteelDevil

+0

@SteelDevil如果回答你的问题,请接受答案。 –

1

可以使用埃拉托色尼算法的筛。这是显示尽可能多的素数的好方法。

相关问题