C program to check whether given number is prime number or not.

Posted by Mangesh on March 14, 2018

/* C program for check whether number is prime number or not. */

Description :

A prime number is a number greater than 1 whose only factors are 1 and itself. Example of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. Numbers that have more than two factors are called composite numbers. The number 1 is neither prime nor composite.

Logic :

To check whether the number is prime or not, we need to divide the number from 2 to square root of the number and if the number is not divisible by any number between the range, then the number is prime number.
Time Complexity is O(sqrt(n)).

Program :

int prime(int number)
  int i;
  for(i = 2; i <= sqrt(number); i++)
  if(number % i == 0)
	return 0;
  return 1;
void main()
   int num, ans = 0;
   printf("Enter a Number to check for Prime Number: ");
   ans = prime(num);
   if(ans == 1)
	printf("%d is prime number.",num); 
	printf("%d is not a prime number.",num);

Output :

c program for prime number` tested in turbo c 3.2

Skills required :

Conditional operators
If-Else statement

Written with from Mangesh.

Related Post
1 C program to check whether given number is prime number or not.
2 C program for Fibonacci Series upto a limited ranges.
3 C program to find whether the number is Armstrong number or not.
4 C program to convert decimal number to octal number.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.