Skip to content

Commit e61d5ea

Browse files
authored
Merge pull request #69 from sccalabr/issue-67
C Program to Check Prime Numbers
2 parents 5a7bbd6 + 87ab4c6 commit e61d5ea

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

C/prime_checker/README.md

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Prime Number Checker
2+
3+
A C program to check if a number is prime or not.
4+
5+
## What it does
6+
7+
Takes a number as input and tells you whether it's prime or not. Pretty straightforward.
8+
9+
## How to compile
10+
11+
```bash
12+
gcc prime_checker.c -o prime_checker -lm
13+
```
14+
15+
The `-lm` flag is needed for the math library.
16+
17+
## Usage
18+
19+
```bash
20+
./prime_checker
21+
```
22+
23+
Then just enter a number when it asks.
24+
25+
## Examples
26+
27+
```
28+
Prime Number Checker
29+
Enter a number: 17
30+
17 is Prime
31+
```
32+
33+
```
34+
Prime Number Checker
35+
Enter a number: 24
36+
24 is Not Prime
37+
```
38+
39+
## How it works
40+
41+
The program checks divisibility up to the square root of the number. If nothing divides it evenly, it's prime. Numbers less than 2 aren't considered prime.
42+
43+
## Test it with these
44+
45+
Some primes to try: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
46+
47+
Some non-primes: 4, 6, 8, 9, 10, 12, 15, 16, 18, 20, 21, 24, 25, 27, 28, 30
48+

C/prime_checker/prime_checker.c

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#include <stdio.h>
2+
#include <stdbool.h>
3+
#include <math.h>
4+
5+
bool isPrime(int num) {
6+
if (num <= 1) return false;
7+
if (num == 2) return true;
8+
if (num % 2 == 0) return false;
9+
10+
int limit = (int)sqrt(num);
11+
for (int i = 3; i <= limit; i += 2) {
12+
if (num % i == 0) return false;
13+
}
14+
15+
return true;
16+
}
17+
18+
int main() {
19+
int number;
20+
21+
printf("Prime Number Checker\n");
22+
printf("Enter a number: ");
23+
24+
if (scanf("%d", &number) != 1) {
25+
printf("Invalid input!\n");
26+
return 1;
27+
}
28+
29+
if (isPrime(number)) {
30+
printf("%d is Prime\n", number);
31+
} else {
32+
printf("%d is Not Prime\n", number);
33+
}
34+
35+
return 0;
36+
}
37+

0 commit comments

Comments
 (0)