当前位置:网站首页>find prime numbers up to n

find prime numbers up to n

2022-07-31 19:28:00 swofford

方法一:基础遍历

用数 i 去除以 2到i-1的每个数,Once the integer isbreak跳出;

		List<Integer> list=new ArrayList<>();
        for(int i=2;i<=n;i++){
    
            boolean a=true;
            for(int j=2;j<i;j++){
    
                if(i%j==0){
    
                    a=false;
                    break; // 跳出循环
                }
            }
            if(a){
     // 假设jIt can traverse to the end without being divisible
                list.add(i);
            }
        }

或者
这种方法 2will not be able to enter the second onefor,所以将2先添加;

		List<Integer> list=new ArrayList<>();
        for(int i=2;i<=n;i++){
    
            if(i==2) list.add(i);
            for(int j=2;j<i;j++){
    
                if(i%j==0){
    
                    break;
                }
                // 如果j It can be traversed to the end without being divisible
                if(j==i-1 && i%j!=0){
    
                    list.add(i);
                }
            }
        }

方法二:用sqrt优化

The factors of integers are large and small,The smaller factor does not exceed the integer平方根,
注意 :j < = Math.sqrt(i) , 有等号 !

		List<Integer> list=new ArrayList<>();
        for(int i=2;i<=n;i++){
    
            boolean a=true;
            for(int j=2;j<=Math.sqrt(i);j++){
    
                if(i%j==0){
    
                    a=false;
                    break; // 跳出循环
                }
            }
            if(a){
     // 假设jIt can traverse to the end without being divisible
                list.add(i);
            }
        }

方法三:用listThe prime numbers in j

继续探索,Questions turn into judgmentsn能否被[2,sqrt(n)]odd integer division between,The composite numbers within these odd numbers are redundant.Because any composite number can be decomposed into the product of several prime numbers in front of it,If it is not divisible by the prime number preceding it,is also not divisible by this composite number.So the divisible range is reduced to [2,sqrt(n)]之间的素数.The purpose of this question is to find prime numbers,Therefore, the obtained prime numbers can be placed in the array for judgment.

注意

  1. j 索引从 0开始 !
  2. 此时 j 是索引 !j 不能等于 list.size()
List<Integer> list=new ArrayList<>();
        for(int i=2;i<=n;i++){
    
            boolean a=true;
            for(int j=2;j<=list.size() && j<=Math.sqrt(i);j++){
    
                if(i%j==0){
    
                    a=false;
                    break;
                }
            }
            if(a){
    
                list.add(i);
            }
        }
原网站

版权声明
本文为[swofford]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/212/202207311920156010.html