A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小白想学javaEE 中级黑马   /  2016-4-8 22:17  /  569 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

分析以下需求,并用代码实现:
        (1)打印1-100之间的所有素数及个数
        (2)每行输出5个满足条件的数,之间用空格分隔
        (3)如果一个大于1的自然数,这个数只能被1和其本身整除,这个数就叫素数。
        (4)如:2 3 5 7 11
       
        class Test2{
                public static void main(String args[]){
                        int x=2,count=0;
                        while (x<100){       
                                x++;
                                for (int y=2;y<x ; y++){
                                        if ((x%y)==0){
                                                break;
                                        }else{
                                                if (y==(x-1)){
                                                        count++;
                                                        System.out.print(x+" ");                                                       
                                                }
                                                continue;
                                        }
                                }
                                if (count==5){
                                        System.out.println("");
                                        count=1;
                                }                                               
                        }
                }
        }
以上是我自己写的,不知道还能不能优化

4 个回复

倒序浏览
顶下 ,川哥, 黑马币拿来
回复 使用道具 举报
class Test2{
                public static void main(String args[]){
                        int x=1,count=0;
                        count++;
                        System.out.print(2+" ");
                        while (x<100){       
                                x++;
                                for (int y=2;y<x ; y++){
                                        if ((x%y)==0){
                                                break;
                                        }else{
                                                if (y==(x-1)){
                                                        count++;
                                                        System.out.print(x+" ");                                                       
                                                }
                                                continue;
                                        }
                                }
                                if (count==5){
                                        System.out.println("");
                                        count=0;
                                }                                               
                        }
                }
        }
回复 使用道具 举报
最开始的代码有两个问题,一个是没把2打印出来,一个是每行只有4个数。修改后的代码解决了以上两个问题。
回复 使用道具 举报
我昨天也是做这个题  没做出来  忍不住看答案了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马