java algorithm-prime number

A prime number is a number that can only be divisible by itself and 1 (1 is not a prime number)

1. Determine whether a number is a prime number

Just need to divide this number by 2 to the radical n. If there is a divisible phenomenon, it is not a prime number, otherwise it is a prime number.

Source code:

	public static int F(int x) {
    
       //判断是否为质数 2,3,5,7,11,13,17,19......
		if(x==1) return 0;
		for(int i=2;i<=x/i;i++)
		{
    
    
			System.out.println(x+ " "+ i);
			if(x%i==0)
				return 0;
		}
		return 1;
	}

In addition to judging whether it is a prime number, we can also decompose prime factors

—————————————————————————————

2. Decompose prime factors

According to the basic theorem of arithmetic, also known as the unique decomposition theorem, for any composite number, we can use the product of the powers of several prime numbers to express.

Algorithm logic description: loop to find the prime factor. When found, the loop will continue to divide by this number, and the number will be recorded. When it is not divisible, exit the loop and continue to find the next prime factor. If the last n is not 1, it means that there is the last prime factor. It is n, outputted.

Source code:

	public static void prime(int n){
    
    
	    for(int i = 2; i <= n / i; i++){
    
          循环到根号n为止
	        int a = 0, b = 0;
	        while(n % i == 0){
    
                    如果可以整除说明是质因数
	            a = i;
	            n /= i;                       一直除以这个数直到不整除为止
	            b++;                          累计a的个数
	        }
	        if(b > 0)
	            System.out.println(a + " " + b);
	    }
	    if(n > 1) System.out.println(n + " " + 1);
	}

enter

24

Output

2 3

3 1

—————————————————————————————

3. Ehrlich screening method

The method of finding prime numbers between 1 and 100 can be repeated 100 times according to the first method of judging prime numbers, and another method is the Ah's screening method.

Algorithm introduction: first create an array, 0 means prime number, 1 means composite number. Start looking for prime numbers from 2, find a prime number and turn all the multiples of 2 into 1, then start looking for prime numbers from 3, and turn all the multiples of 3 into 1...

For example, find prime numbers between 1 and 18

First filter out multiples of 2, 4, 6, 8, 10, 12, 14, 16, 18, then filter out multiples of 3, 6, 9, 12, 15, 18, and then filter out multiples of 5, 10, 15 , And so on to cycle to 18.
	static int st[] = new int [100];        //0表示质数,1表示合数
	static int n;
	public static void E(int n) {
    
    
		for(int i=2;i<=n;i++) {
    
    
			if(st[i]==0)                    //第一轮,2开始,4,6,8,10,12...20被筛选
			{
    
                                   //第二轮,3开始,6,9,12,15,18被筛选
				for(int j=2*i;j<=n;j+=i)    //第三轮,5开始,10,15,20被筛选
					st[j]=1;
				}
		}
	}

Guess you like

Origin blog.csdn.net/weixin_44919936/article/details/109751883