Implementation of algorithm for determining prime numbers

A prime number is a number that has only two factors: 1 and itself. You can determine whether a number is prime by the following methods:

  1. Trial division: Divide the number by every integer between 2 and its square root. If it is not divisible, the number is prime.

  2. Fermat's Little Theorem: If p is a prime number and a is an integer not divisible by p, then a^(p-1)-1 is divisible by p.

  3. Miller-Rabin primality test: For an integer n, let n-1=d·2s, where d is an odd number and a is from 2 to n-2 A random integer, if ad mod n = 1 or there is an r (0<=r<=s-1), such that a((2 r)·d) mod n = -1, then n may be a prime number. Repeat this test k times. If each test returns the result that n is a prime number, then n is is considered a prime number.

The above are common methods for determining prime numbers, but for particularly large numbers, more complex algorithms may be required.

Insert image description here

1. C implementation to determine prime numbers and code details

A prime number, also known as a prime number, refers to a positive integer that can only be divided by 1 and itself. The following is the code for determining prime numbers in C language:

#include <stdio.h>
#include <stdbool.h>

bool isPrime(int n) {
    
    
    if(n <= 1) {
    
    
        // 1不是素数
        return false;
    }
    for(int i=2; i*i<=n; i++) {
    
    
        if(n % i == 0) {
    
    
            // 若n能被i整除,则n不是素数
            return false;
        }
    }
    return true;
}

int main() {
    
    
    int n;
    printf("请输入一个正整数:");
    scanf("%d", &n);
    if(isPrime(n)) {
    
    
        printf("%d是素数\n", n);
    } else {
    
    
        printf("%d不是素数\n", n);
    }
    return 0;
}

Code explanation:

  1. Quotestdbool.h header file, use bool type instead of int type return value.
  2. isPrimeThe function determines whether the input positive integer n is a prime number. If it is less than or equal to 1, it is not a prime number; otherwise, it starts looping from 2. If there is i that can divide n, then n is not a prime number; otherwise, n is a prime number.
  3. mainRead a positive integer into the functionn, call the isPrime function to make a judgment and output the result.

In the loop, only need to judge i 2 i^2 i2Yes or no Dayu n n n,Because it is the result i 2 i^2 i2Dayu n n n i i igive n n The factors of n must have already appeared, so there is no need to continue the loop judgment. This can reduce the running time of the code.

2. C++ implementation of determining prime numbers and detailed code explanation

Determining prime numbers refers to determining whether a number is prime, that is, a number that can only be divided by 1 and itself. The following is the code for determining prime numbers in C++:

#include <iostream>
#include <cmath>
using namespace std;

bool is_prime(int n) {   // 判断素数函数
    if (n <= 1) return false;   // 如果小于等于1,则不是素数
    int sqr = sqrt(n);          // 计算n的平方根
    for (int i = 2; i <= sqr; i++) {
        if (n % i == 0) return false;  // 如果n能被i整除,则不是素数
    }
    return true;  // 否则是素数
}

int main() {
    int n;
    cout << "请输入一个正整数:";
    cin >> n;
    if (is_prime(n)) {
        cout << n << " 是素数" << endl;
    } else {
        cout << n << " 不是素数" << endl;
    }
    return 0;
}

In the above code, the main function is is_prime(), which is used to determine whether a number is prime. First, judge the special situation, that is, the input number is less than or equal to 1, and return false directly. Then calculate the square root of the input number, and loop from 2 to the square root to determine whether it can be divisible. If so, return false directly. Finally, true is returned, indicating that the input number is a prime number.

In the main function, first input a positive integer n from the keyboard, and then call the is_prime() function to make a judgment. If it is a prime number, output the result, "n is a prime number", otherwise output "n is not a prime number".

Through the above code for judging prime numbers in C++, we can better understand the definition and judgment method of prime numbers.

Insert image description here

3. Java implementation of determining prime numbers and code details

A prime number is a number that is only divisible by 1 and itself. In Java, you can use enumeration or trial division to determine whether a number is prime.

  1. Enumeration method

The enumeration method is the most basic method of judging prime numbers. It starts from 2 and continues to the square root of the number. If there are factors of the number, the number is not a prime number; otherwise, the number is a prime number.

The Java code is implemented as follows:

public static boolean isPrime(int num) {
    
    
    if (num <= 1) {
    
    
        return false;
    }
    for (int i = 2; i <= Math.sqrt(num); i++) {
    
    
        if (num % i == 0) {
    
    
            return false;
        }
    }
    return true;
}
  1. trial division

The trial division method is optimized based on the enumeration method. For each number, you only need to enumerate the prime numbers less than or equal to its square root. Because if the number has a factor greater than its square root, then there must be a factor less than its square root.

The Java code is implemented as follows:

public static boolean isPrime(int num) {
    
    
    if (num <= 1) {
    
    
        return false;
    }
    if (num == 2 || num == 3) {
    
    
        return true;
    }
    if (num % 6 != 1 && num % 6 != 5) {
    
    
        return false;
    }
    for (int i = 5; i <= Math.sqrt(num); i += 6) {
    
    
        if (num % i == 0 || num % (i + 2) == 0) {
    
    
            return false;
        }
    }
    return true;
}

The 6k-1 and 6k+1 rules are used here for optimization, that is, a number is prime if and only if it is in the form of 6k-1 or 6k+1. This regular optimization can reduce the number of traversals by half.

The above are the two methods and code details for judging prime numbers in Java.

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_47225948/article/details/133124907