C language - judging prime numbers (prime numbers)

To determine whether a number is prime (prime number), you can use the following algorithm:

  1. First, determine whether the number is less than or equal to 1. If it is less than or equal to 1, it is not a prime number.

  2. Then, starting from 2, determine whether this number is divisible by a number smaller than it. If it is divisible, it is not a prime number.

  3. The range of judgment can be limited to less than or equal to the square root of this number.

The following is sample code written in C language:

#include <stdio.h>
#include <math.h>

int isPrime(int num) {
  if (num <= 1) {
    return 0;
  }
  
  int i;
  int sqrt_num = sqrt(num);
  for (i = 2; i <= sqrt_num; i++) {
    if (num % i == 0) {
      return 0;
    }
  }
  
  return 1;
}

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

In the above code, isPrime function is used to determine whether a number is a prime number. The return result is 1, which means it is a prime number, and the return result is 0, which means it is not a prime number. The main function gets an integer from user input, calls the isPrime function to make a judgment, and outputs the result.

This code can be divided into two parts for analysis: isPrime function and main function.

isPrime function

int isPrime(int num) {
  if (num <= 1) {
    return 0;
  }
  
  int i;
  int sqrt_num = sqrt(num);
  for (i = 2; i <= sqrt_num; i++) {
    if (num % i == 0) {
      return 0;
    }
  }
  
  return 1;
}

This function is used to determine whether an integer is prime. It accepts an integer as a parameter and returns an integer as the judgment result (1 represents a prime number, 0 represents a non-prime number). The function first checks whether the input number is less than or equal to 1. If so, it returns 0 directly. Then it uses a loop to check whether the input number is divisible one by one starting from 2. The range of the loop is limited to less than or equal to the square root of the input number. If it is divisible, 0 is returned, otherwise 1 is returned.

main function

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

This function is the entry point of the program. It prompts the user to enter an integer, and then determines whether the input integer is a prime number by calling the isPrime function. According to the return value of the isPrime function (1 or 0), the corresponding result is output.

Guess you like

Origin blog.csdn.net/weixin_66547608/article/details/134913785