黑马程序员技术交流社区

标题: 素数的求解 [打印本页]

作者: 小b,试试就试试    时间: 2016-7-28 21:57
标题: 素数的求解
分析以下需求,并用代码实现:
        (1)打印1-100之间的所有素数及个数
        (2)每行输出5个满足条件的数,之间用空格分隔
        (3)大于1且只能被1和其本身整除的数叫素数
        (4)如:2 3 5 7 11
                        public class Test03 {
                                public static void main(String[] args) {
                                        //1.定义计数器统计素数的个数
                                        int count = 0;
                                        //2.遍历判断是否是素数并打印
                                        for (int i = 2; i < 100; i++) {

                                                if (isPrime(i)) {
                                                        count++;
                                                        System.out.print(i + " ");

                                                        if(count%5==0) {        //放在if语句外面呢?
                                                                System.out.println();
                                                        }
                                                }

                                        }
                                        System.out.println();
                                        System.out.println("1-100的素数的个数为:" + count);
                                }

                                //判断是否是素数的方法
                                public static boolean isPrime(int num) {
                                        for (int x = 2; x < num; x++) {// 从2到99来寻找
                                                if ((num % x) == 0) {
                                                        return false;
                                                }
                                        }
                                        return true;
                                }
                        }
作者: 小b,试试就试试    时间: 2016-7-28 21:59
以前要是有的话,那不一定对




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2