Prime Number in C
Welcome to this tutorial where you will learn how to find prime numbers using the C programming language. Prime numbers are an essential concept in mathematics and computer science, and they are widely used in many programming tasks, including cryptography, data compression, and more.
In this tutorial, we will provide you with a comprehensive guide to finding prime numbers using C programming language. We will cover different methods to perform this operation, including using loops and functions. You will learn how to write a C program to find prime numbers and also provide you with clear explanations and easy-to-understand examples.
What is a Prime number?
Prime numbers are numbers that have only 2 factors: 1 and themselves.
For example:
The first 5 prime numbers are 2, 3, 5, 7, and 11.
By contrast, numbers with more than 2 factors are called composite numbers.
Program for Prime numbers:
// To find out if a given number is prime or not
#include <stdio.h>
#include <math.h>
int main() {
int n, i, isPrime = 1; // assume number is prime initially
printf("Enter a number: ");
scanf("%d", &n);
if (n <= 1) {
isPrime = 0; // numbers <= 1 are not prime
} else {
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
isPrime = 0; // found a divisor, not prime
break;
}
}
}
if (isPrime) {
printf("%d is a prime number.\n", n);
} else {
printf("%d is not a prime number.\n", n);
}
return 0;
}
Output:
Enter the number: 3
3 is a prime number
0 Comments