facebook like button

27 March, 2011

program 17: finding out whether a number is prime or not

The need:
     Till now you have a clear idea about loops. Now lets implement this knowledge to a program that will be doing some more than a calculator or human. Here is a program that will ask the user to enter an integer and will tell whether the number entered is a prime number or not. This program was given as assignment in the lab.

The code: 
--------------------------------------------
#include<stdio.h>
main()
{
    int i,j,k=0;
    printf("Enter the number...");
    scanf("%d",&i);
    for(j=2;j<i/2;j++)
    {
         if(i%j==0)
         k++;
    }
         if(k>=1)
         printf("The number is not a prime number.\n\n");
        else
        printf("The number is a prime number.\n\n");
}-----------------------------------------

The approach:
   A number will be prime if it can not be fully divided by any number except itself and 1. So in this program I have checked for 2 to i/2 where i is the given number because we already know that any number 'i' cannot be fully divided by any other number lying in range of i/2 and i (both exclusive). Except that again I am using a counter 'k' which is incremented whenever a number which completely divide 'i' is found.
   After the loop finishes, value of 'k' is checked. If it(value of k) is more than its value at the start( at starting of program k=0) then in above specified range 'k' numbers that divide 'i' fully has been found which implies that 'i' is a not prime number otherwise if it(value of k) is same as start( at starting of program k=0) then in above specified range no number that divide 'i' fully has been found which implies that 'i' is a prime number.

Remarks:
1. This is basic program to check whether a number is prime or not. This program is not 100% correct and says 2 is not a prime number.
2. I gave this program like this because at that time I made it in this way. You'll come to know more by going sequentially through this blog.
3. The idea was to show the use for loop and not confuse beginners with if and else conditions with looping.
 The more efficient and 100% correct program to find whether a number is prime or not is given in the post referenced by the following link.
program 24.

2 comments:

  1. The loop needs to run till (int)sqrt(i) IMO, but checking for excess cases doesn't really harm anything :)

    ReplyDelete
  2. Yes, you are right. I am glad that you people are also reading this. This just like proofreading. But up-till this point of time people are not supposed to know about sqrt() as I have not introduced them with 'math.h' till now.

    ReplyDelete

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply