Can someone test this code and see why it's not working? Your supposed to enter a number, and it tells you if it's prime or not. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can someone test this code and see why it's not working? Your supposed to enter a number, and it tells you if it's prime or not.

#include <iostream> using namespace std; int main(){ int div=2; int num; bool sw = true; cout<<"Please enter a number:"<<endl; cin>>num; do{ if(num%div>0){ ++div; } else{ sw=false; } }while(div<num&&num%div>0); if(sw==true){ cout<<num<<" is a prime number."; } else{ cout<<num<<" is not a prime number."; } return 0; }

26th Jul 2018, 2:05 AM
Thomas Wald
Thomas Wald - avatar
6 Answers
+ 1
why can't you go with for loop ? one more thing is that one need to check for half of the input number... for example, for 10 as input, modulo need to be check for 5 only to decide 10 as prime number... Half of number is less efficient compared to square root of number... check till 3 only for 10 as input and you are done..
26th Jul 2018, 1:46 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
You shouldn’t use do...while. Try inputing 2 and seeing why that doesn’t work.
26th Jul 2018, 2:51 AM
Alexander
Alexander - avatar
0
The more important bug is that suppose num is 9, and div is 2. num % div is not 0, so increment div. Now div is 3, and the while condition finds that num % div is 0, so it breaks out of the loop! We have not set sw to false yet, so the program says it’s prime.
26th Jul 2018, 2:58 AM
Alexander
Alexander - avatar
0
Please fix your coding style, it is what caused your error. Here's a cleaned and working version. #include <iostream> using namespace std; int main() { int div=2; int num; bool sw = true; cout << "Please enter a number: " << endl; cin >> num; do { if(num % div > 0) ++div; else sw = false; } while(div < num && num % div > 0); if (sw == true) cout << num <<" is a prime number.\n"; else cout << num << " is not a prime number.\n"; return 0; }
26th Jul 2018, 3:01 AM
apex137
apex137 - avatar
0
So, what should I use instead of a do while loop?
26th Jul 2018, 3:57 AM
Thomas Wald
Thomas Wald - avatar
0
Just a while loop. Do while always enters the loop at least once, but you should not enter the loop when num == 2
26th Jul 2018, 3:58 AM
Alexander
Alexander - avatar