Click here to Skip to main content
15,894,825 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
i want user to enter number and check if that number is prime or not

but my code show wrong result so what is wrong with my code
i know that i missed thing but do not know it

C#
#include<stdio.h>
#include<conio.h>
int main()
    {
      int num,i,isPrime=0;
      clrscr();
      printf("please enter the number you check prime \n");
      scanf("%d",&num);
      if(num <= 1)
       printf("the number %d is not prime",num);
     else if(num == 1)
       printf("the number %d is not prime",num);
     else if(num == 2)
       printf("the number %d is prime",num);
      else{
       for(i=3;i*i<= num ;i++)
       {
         if(num % i == 0)
          {
            isPrime= 0;
            break;
          }


       }
       if( isPrime == 0)
            printf("the number %d is  prime",num);
        else
           printf("the number %d is not prime",num);
       }
       getch();
      return 0;
    }
Posted

You should initialize isPrime with a non-zero value, change from:
Quote:
int num,i,isPrime=0;
to
C
int num,i,isPrime=1;



[update]
There are other two errors.
Change from:
Quote:
for(i=3;i*i<= num ;i++)
to
C
for(i=2;i*i<= num ;i++)


and from
Quote:
if( isPrime == 0)
to
C
if( isPrime == 1)

[/update]
 
Share this answer
 
v2
Comments
nv3 2-Oct-14 9:14am    
That's it! 5.
CPallini 2-Oct-14 9:20am    
Thank you.
TheSniper105 2-Oct-14 15:42pm    
the result still wrong try numbers like 10 and 11 you will see the result same
CPallini 2-Oct-14 16:13pm    
There are indeed other errors. See my updated answer.
TheSniper105 2-Oct-14 16:10pm    
and here is the code after modify it
http://pastebin.com/SmWRNYVH
In addition to CPallini's solution, there's a bug when num is 1.

Change this:

C++
if(num <= 1)


... to this ...

C++
if(num < 1)
 
Share this answer
 
Comments
TheSniper105 2-Oct-14 15:42pm    
the result still wrong try numbers like 10 and 11 you will see the result same
TheSniper105 2-Oct-14 16:10pm    
and here is the code after modify it
http://pastebin.com/SmWRNYVH

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900