Program to Check Whether a Number is Prime or Not in C
Prime Number :
Prime Number is defined as the number which is divisible by itself and by one only. It should not be divisible by any other number.
Working of Program :
In the program, we will take a value from the user and use loop and conditional statement to check whether a number is prime or not.
Run
#include<stdio.h> int main() { int val; printf("Enter the number to be checked :"); scanf("%d", &val); for(int i=2; i < val; i++){ if(val%i ==0){ printf("Given Number %d is not prime number", val); return 0; } } printf("Given Number %d is a Prime Number", val); return 0; }
Output :
Enter the number to be checked : 17 17 Given Number 17 is a Prime Number
What Happened Above?
In the Above Program, we follow the following steps to check the Prime Number :
In Step 1, we take the value from user. In step 2, by using for loop we check whether the number is divisible by 2 to given number , if yes then it will not be a prime number. In step 3, if we move out of the loop then it is sure that it will be a prime number.
Example :
Let’s solve the same problem by same algorithm but this time, we optimize the code little bit by running the for loop to square root of n times.
Run
#include<stdio.h> int main() { int val; printf("Enter the number to be checked :"); scanf("%d", &val); for(int i=2; i*i < val; i++){ if(val%i ==0){ printf("Given Number %d is not prime number", val); return 0; } } printf("Given Number %d is a Prime Number", val); return 0; }
Output :
Enter the number to be checked : 17 17 Given Number 17 is a Prime Number
What Happened Above?
In the above program, we optimize the program by running the for loop for square root of n times instead of n time as number should be divisible by factor to divide by any number between 2 and given number
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others