C Programming for Prime Numbers
Prime numbers are natural numbers greater than 1 that are only divisible by 1 and themselves. In this article, we will discuss how to write C code to identify prime numbers using different approaches.
Approach 1: Brute force method The brute force method involves checking if a number n is divisible by any number between 2 and n-1. If n is divisible by any number between 2 and n-1, then it is not a prime number. Otherwise, it is a prime number.
Code implementation: The following code implements the brute force method to identify prime numbers:
#include <stdio.h>
#include <math.h>
int isPrime(int n)
{
int i;
// check if n is a multiple of 2
if (n % 2 == 0) {
return 0;
}
// check for all odd numbers
for (i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
flag = isPrime(n);
if (flag == 1) {
printf("%d is a prime number.", n);
}
else {
printf("%d is not a prime number.", n);
}
}
return 0;
}
In this code, we first take input from the user and check if the number is 0 or 1 (which are not prime numbers). Then we iterate from 2 to n/2 and check if n is divisible by any number between 2 and n/2. If n is divisible, we set the flag to 1 and break out of the loop. Finally, we check the value of the flag to determine if n is a prime number.
Approach 2: Optimized brute force method The optimized brute force method involves checking if a number n is divisible by any prime number between 2 and sqrt(n). If n is divisible by any prime number between 2 and sqrt(n), then it is not a prime number. Otherwise, it is a prime number.
Code implementation: The following code implements the optimized brute force method to identify prime numbers:
#include <stdio.h>
#include <math.h>
int isPrime(int n)
{
int i;
// check if n is a multiple of 2
if (n % 2 == 0) {
return 0;
}
// check for all odd numbers
for (i = 3; i <= sqrt(n); i += 2) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main()
{
int n, flag;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
flag = isPrime(n);
if (flag == 1) {
printf("%d is a prime number.", n);
}
else {
printf("%d is not a prime number.", n);
}
}
return 0;
}
In this code, we first take input from the user and check if the number is 1. If the number is 1, we print a message saying that 1 is neither prime nor composite. Otherwise, we call the isPrime function to determine if the number is prime or not. In the isPrime function, we first check if the number is a multiple of 2. If