Home  >  Article  >  Java  >  Java prints all prime numbers within N

Java prints all prime numbers within N

王林
王林forward
2020-10-26 16:06:402531browse

Java prints all prime numbers within N

Question:

Print out all prime numbers within N

(Video tutorial sharing: java course)

Idea:

The definition of a prime number is that its factors are only 1 and itself, so when we judge, we can judge based on whether the number traversed has factors other than 1 and itself. At the same time, we know that if there is a factor (that is, if it is a composite number), then the factor must be smaller than this number, and we will eliminate it.

Code implementation:

package Algorithm.Interview;

import java.util.ArrayList;
import java.util.List;

public class primeNum {
    public List PrintPrime(int n){
        List Prime = new ArrayList<>();
        //2也是质数
        Prime.add(2);
        //外循环遍历N以内的所有数,1不是质数,2是质数,所以从2开始遍历
        for (int i = 2; i <= n; i++) {
        //内循环遍历小于要判断的数的因子,即要判断的数是否有除了1和它本身的因子
            for (int j = 2; j < i; j++) {
            	//如果有因子,直接跳出内循环,到外循环遍历下一个数
                if (i % j == 0){
                    break;
                }
                //如果没有因子,判断j = i-1这个数,能循环到i-1说明之前的j都没有跳出循环,来判断最后一个小于i的数是不是i的因子
                else if (j == i -1 && i % j != 0){
                    Prime.add(i);
                }
            }

        }
        return Prime;
    }

    public static void main(String[] args) {
        primeNum primeNum = new primeNum();
        System.out.println(primeNum.PrintPrime(100));
    }
}

Related recommendations:Getting started with java

The above is the detailed content of Java prints all prime numbers within N. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete