Java经典算法40例(二)

来源:互联网 发布:2017年淘宝测黑号 编辑:程序博客网 时间:2024/06/16 12:24

素数问题:判断101-200之间有多少个素数,并输出所有素数。

分析:
判断素数:要判断x是否为素数,只要让x除2到根号x的所有数,如果都不能整除,则x是素数。

代码:

/** * 101-200之间素数的和 * @author cheng * */public class Two {    public boolean sushu(int x){  //判断素数        for(int i=2;i<=Math.sqrt(x);i++){            if(x%i==0)                return false;        }        return true;    }    public static void main(String[] args){        Two two=new Two();        int sum=0;        for(int m=101;m<=200;m++){            if(two.sushu(m)==true){                System.out.println(m);                sum+=m;            }        }        System.out.println("sum="+sum);    }}

输出结果:

101103107109113127131137139149151157163167173179181191193197199sum=3167
原创粉丝点击