-->
Showing posts with label to test a number is prime or not. Show all posts
Showing posts with label to test a number is prime or not. Show all posts

program to test whether a number is prime or not.

//program to test whether a number is prime or not.
#include<stdio.h>
include<conio.h>
void main()
{
   int n,count=0,i;
   printf("enter a number for 'n'\n");
  scanf("%d",&n);
  for(i=2;i<n;i++)
    {
      if(n%i==0)
        {                
            count=1;
        }
   }
if(count==0)
{
printf("it's prime\n");
}
else
{
printf("it's not");
}
getch();
}
--------------------------------------------------------------------------------------------------------------------------------------
logics in mind:
a prime number is that which is divisible by '1' and itself. It means there are only two numbers which can divide that given number. And any 3rd number is not there.
so here we check whether 3rd number is there or not.
->enter a number to be checked
->declare a variable with an initial value 0(u can use any other value)
-> use repetitive process from number 2 to one less than entered number 'n' i.e we divide given number 'n by 2,3... and n-1. This we can apply using loop as shown above.If we get zero as remainder while dividing then we assign value '1' to count.
->later, as the loop terminates then we check whether 'count' has got value 0 or 1.If it has '0' it means it is prime and if it has 1 then it is not prime.

we can also use following technique.
//program to test whether a number is prime or not.
#include<stdio.h>
include<conio.h>
void main()
{
   int n,count=0,i;
   printf("enter a number for 'n'\n");
  scanf("%d",&n);
  for(i=1;i<=n;i++)
    {
      if(n%i==0)
        {                
            count++;
        }
   }
if(count==2)
{
printf("it's prime\n");
}
else
{
printf("it's not");
}
getch();

}
----------------------------------------
logics in mind:
->here, we have used same concept but in different way.
->we have used value from 1 to entered number 'n' in loop to count total numbers which can divide entered number
->obviously if count is 2 then it is prime and if not then it is not