| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Prime number checker
This is my first c program I have done totally by myself and prime point
of this program is to check if number(which user enter) is prime number or not. I have done this kind of program before with Visual Basic but it's so slow language so I decided to make one with c. Problem I have is that it always says that it's not prime number. Here's the source: ************************CODE******************* #include <iostream.h> void main() { int a, i, o; o=0; cout << "Give number\n"; cin >> a; for (i = 1; i<a; i++) { if ((a % i) == 0) { o=1; break; } } if (o==1) cout << "Not prime number\n"; else cout << "prime number\n"; } ********************END OF CODE*************** I can't figure out the reason, please help me. |
|
#2
|
|||
|
|||
|
This is happening because the loop goes from 1 to a. In the first iteration with i = 1 the if statement will read if (their_number % 1) == 0) which will always be true regardless of the value of their_number.
To avoid this problem run it from 2 instead of 1. -KM- |
|
#3
|
|||
|
|||
|
Thank you!
Now it works
thank you! |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Prime number checker |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|