Home >Backend Development >C++ >How Can I Determine if a Number is Prime in C?
Determining the Primality of a Number in C
You seek a method in C to discern whether a given integer is prime or not. For the uninitiated, a prime number is an integer greater than one that is divisible only by itself and one.
Algorithm
Before delving into C code, let's outline the algorithm for prime checking:
C Implementation
Armed with our algorithm, let's translate it into C:
#include <stdio.h> int isPrime(int number) { if (number <= 1) return 0; // 0 and 1 are not prime int i; for (i = 2; i * i <= number; i++) { if (number % i == 0) return 0; } return 1; } int main() { int num; printf("Enter an integer: "); scanf("%d", &num); printf("%d is %s\n", num, isPrime(num) ? "prime" : "not prime"); return 0; }
Explanation
Example Usage
Input: 13
Output: 13 is prime
Input: 9
Output: 9 is not prime
The above is the detailed content of How Can I Determine if a Number is Prime in C?. For more information, please follow other related articles on the PHP Chinese website!