题解 | #判断素数个数#

判断素数个数

http://www.nowcoder.com/practice/c6ad83181a17408eb7605d51a251dd9a


public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int start = scanner.nextInt();
        int end = scanner.nextInt();
        method(start,end);
    }

    public static void method(int start, int end) {
        int count=0;
        int i;
        int t;
        if(start>end){
            t=start;
            start=end;
            end=t;
        }
        for(i=start;i<=end;i++){
            if(judge(i)==true){
                count+=1;
            }
        }
        //write your code here......
        System.out.println(start+"到"+end+"之间有"+count+"个大于2的素数");
    }
    
    public static Boolean judge(int num){
        boolean flag=false;
        int i;
        int count=0;
        for(i=1;i<=num;i++){
            if(num%i==0){
                count+=1;
            }
        }
        if(count==2){
            flag=true;
        }
        else{
            flag=false;
        }
        
        if(num==2){
            flag=false;
        }
        return flag;
    }
}
全部评论
其实可以从2开始遍历到num-1就可以,用1到num反而复杂了
点赞 回复 分享
发布于 2023-07-14 00:21 广东

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务