Home > Backend Development > C++ > How to Determine if a Number is Prime in C?

How to Determine if a Number is Prime in C?

DDD
Release: 2024-12-31 22:10:15
Original
306 people have browsed it

How to Determine if a Number is Prime in C?

Determining Prime Numbers in C

To ascertain whether a given integer is prime, let's start by outlining the steps involved:

  1. Initialize a loop variable i to 2.
  2. Test if i is less than the input number number.
  3. Check if number modulo i equals zero, indicating potential non-primality.
  4. Handle the exception case where i equals number, which cannot disprove primality.
  5. Increment i and repeat steps 2-4.
  6. Return true (or 1) if no divisors were found, indicating the number is prime; else, return false (or 0).

Now, let's translate this algorithm into C code:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // Handle special cases
    unsigned int i;
    for (i = 2; i*i <= number; i++) {
        if (number % i == 0) return 0; // Number has divisors
    }
    return 1; // No divisors found, number is prime
}
Copy after login

This function follows the outlined steps:

  • It handles negative and special cases (0 and 1 are not prime).
  • It iterates through potential divisors up to the square root of number.
  • It efficiently tests for exact divisors.

While this method is not optimized for performance, it provides a clear and comprehensible solution for determining prime numbers in C.

The above is the detailed content of How to Determine if a Number is Prime in C?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template