Reputation: 31
I understand I can just use for-loop to define prime number, but before I implement for loop into that topic, I had a thought that I maybe could make one with while loop or do-while. Somehow, my do-while loop seems not to be working correctly.
My theory was that I could find prime number for checking the remainder of divisor where divisor keeps decreasing by 1 until divisor reaches 1. (Although 'until divisor reaches 1.' part is not in the code, I would assumed remainder of 0 would appear anyway before divisor goes below 0.)
However, it keeps halting before remainder reaches 0.
What did I do wrong?
I've even tried both instead of (remainder<1 && remainder!=1)
below but still no luck.
while (remainder<1)
while (remainder==1)
#include <iostream>
using namespace std;
int main()
{
int number, divisor, remainder;
cin >> number;
divisor=number-1;
cout << "You've put " << number << ".\n";
do {
divisor = divisor - 1;
remainder=number%divisor;
}
while (remainder<1 && remainder!=1);
cout << divisor << " " << remainder << " " << number << " " << "Divisor, remainder, number\n";
return 0;
}
Upvotes: 0
Views: 1040
Reputation: 780655
First, you have a typo in your variable assignment. This line:
number = divisor - 1;
should be:
divisor = number - 1;
The while()
condition should be while (remainder != 0)
, so that the loop keeps repeating as long as you haven't found a divisor. If you want to be more explicit, you could use while (divisor > 1 && remainder != 0)
. There's no need to repeat when divisor == 1
because that's a divisor of all integers.
Upvotes: 3