Without even considering whether your approach is correct or not:
Line 12: You don't initialize rem
Line 17: You loop as long as rem is 0. First of all, rem is never zero as you didn't initialize it, second, I think this condition doesn't make much sense. If at all, you'd want to loop as long as rem is not zero.
Also, you never update num's value, so in line 19 you always get the same rem, which will make it loop infinitely eventually - if your condition was appropriate, that is.
Here's how I did it (I won't give out the solution yet so you can try it for yourself):
1.) You don't need rem at all, just work with num.
2.) Make a if/else branch. First check whether it's not divisible by either two or three. That's the trivial case. Otherwise you'll have to compute the 2s and 3s.
Well, since someone else already did it, I might as well share my approach x)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int num = 0; //User entered number
int two = 0; //Counter for 2's
int three = 0; //Counter for 3's
cout << "Eneter a positive integer: ";
cin >> num;
// if it's not divisible by either, then just say so
if(num%2 != 0 && num%3 != 0) {
cout << "NO!" << endl;
// otherwise do the computation
} else {
while(num%2 == 0 || num%3 == 0) { // loop as long as num is divisible by either one
if(num%2 == 0) {
two++;
num = num/2; // don't forget to update accordingly!
} else {
three++;
num = num/3;
}
}
// I forgot this!
if(num == 1)
std::cout << "Yes." << std::endl;
else
std::cout << "No." << std::endl;
// (*)
}
// this will be printed out every time. If you don't want that, put this to (*)
cout << "number 2s " << two << endl;
cout << "number 3s " << three << endl;
return 0;
}
| |