判断素数的常规方法

素数就是其本身除了被1和它本身之外的任何整数都不能整除

1. 遍历法:

通过遍历从1到它身的数,再用被判断的数取整除这些数,通过计数器的方式,判断是否等于2,来判断是否为素数(最容易理解的方法,时间复杂度也最高)

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int temp = scanner.nextInt();
        for(int i= 0;i<temp;i++){
            int num = scanner.nextInt();
            int count = 0;
            for(int j = 1;j<=num;j++){
                if(num%j==0){
                    count++;
                }
            }
            if(count == 2){
                System.out.print("Yes");
            }else{
                System.out.print("No");
            }
        }

    }
}

2.简化后

除了1以外,任何合数最小的因子就是2,那最大的因子就是 n/2
那我们就从2开始遍历到 n/2就足够了

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int temp = scanner.nextInt();
        for(int i= 0;i<temp;i++){
            int num = scanner.nextInt();
            int count = 0;
            for(int j = 2;j<=num/2;j++){
                if(num%j==0){
                    System.out.println("Yes");
                }else{
                    System.out.println("No");
                }
            }
            
        }

    }
}

3.再进一步

其实不需要遍历到n/2,只需要遍历到根号n,就可以进行判断(降低时间复杂度)

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int temp = scanner.nextInt();
        for(int i= 0;i<temp;i++){
            int num = scanner.nextInt();
            int count = 0;
            for(int j = 1;j<=(int)(Math.sqrt(num));j++){
                if(num%j==0){
                    System.out.println("Yes");
                }else{
                    System.out.println("No");
                }
            }
            
        }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值