算法小题2→素数

来源:互联网 发布:淘宝管控交易风险保障 编辑:程序博客网 时间:2024/05/19 12:36

题目:判断101-200之间有多少个素数,并输出所有素数。
程序分析:判断素数的方法:用一个数分别去除2到sqrt(这个数),如果能被整除, 则表明此数不是素数,反之是素数。
   
public class lianxi02 {
public static void main(String[] args) {
    int count = 0;
    for(int i=101; i<200; i+=2) {
     boolean b = false;
     for(int j=2; j<=Math.sqrt(i); j++)
     {
        if(i % j == 0) { b = false; break; }
         else           { b = true; }
     }
        if(b == true) {count ++;System.out.println(i );}
                                  }
    System.out.println( "素数个数是
: " + count);
}
}

PS:

 有事会遇到1—100之间的素数、看清楚了、换个数字即可。

明白其中的逻辑才是最重要的。

解决一个问题的途径不止一种、类似素数的题还有其他的解法、

例如:

 

public static void main(String[] args) {
  for (int i = 1; i <= 100; i++) {
   boolean fg = true;
   for (int j = 2; j < i; j++) {
    if (i % j == 0) {
     fg = false;
     break;
    }
   }
   if (fg == true)
    System.out.println( + i);
  }
 }

 

 

天热了、喝饮料吧。

http://my.csdn.net/se_xiaofeng   Welcome to my blog!

 

原创粉丝点击