当前位置:   article > 正文

素数的时间复杂度分析_分析判断n是否为素数,n≥0 算法的时间复杂度

分析判断n是否为素数,n≥0 算法的时间复杂度

找出素数的四种方法:

复杂度 主要区别
1. 时间复杂度:O(n2) divisor <= Math.sqrt(number)
2. 时间复杂度:O(n√n) divisor <= squareRoot,其中squareRoot2 <number
3. 时间复杂度:O(n√n / logn) for (int k=0; k<list.size() && list.get(k) <= squareRoot ;k++){…}
4. 时间复杂度:O(n√n / logn) for (int i=k; i<= n/k; i++){ //执行了 n/k-(k-1) primes[k * i] = false;
1、时间复杂度:O(n2)
  • divisor <= Math.sqrt(number)
public class PremeNumber {
   
    public static void main(String[] args) {
   
        final int NUMBER_OF_PRIMES = 50 ;
        final int NUMBER_OF_PRIMES_PRE_LINE = 10;
        int count = 0;
        int number = 2;
        System.out.println("The first 50 prime numbers are : ");

        while (count < NUMBER_OF_PRIMES){
   
            boolean isPrime = true;
            for (int divisor = 2; divisor <= Math.sqrt(number); divisor++){
   
                if (number % divisor == 0){
   
                    isPrime = false;
                    break;
                }
            }
            if (isPrime){
   
                count++;
                if (count % NUMBER_OF_PRIMES_PRE_LINE == 0){
   
                    System.out.println(number);
                }
                else System.out.print(number+" ");
            }
            number++;
        }
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
2、时间复杂度:O(n√n)

1. 主要区别:

int  squareRoot = 0;         
if (squareRoot * squareRoot < number) squareRoot++;
   for (int divisor = 2; divisor <= squareRoot; divisor++){
   
  • 1
  • 2
  • 3
  • 4

2.完整代码:

public 
    声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/75255
    推荐阅读
    相关标签
      

    闽ICP备14008679号