The questions is: obtain the number of divisions performed (converting decimal to octal) to get the octal form. I have a c++ program that already does decimal to octal, but idk how to show how many divisions (or times the program goes through the algorithm). Any help?
easiest way - store a global variable, say numOfDiv. Every time you perform a division, increment the variable. That's all
could you give an example...it doesn't have to pertain to my solution, its just been over a year since I have been programming and I cant find anything on google search
OK, I'll write a program that does, ermm... say, prime-factorization Code: #include <iostream> int main() { using namespace std; int n; cin >> n; cout << n << " = 1" ; for(int i = 2; i * i <=n ;++i) { while(n%i == 0) { cout << " * " << i; n /= i; //n = n/i } } if(n > 1) cout <<" * " << n; cout << endl; cin.get(); } So, if you wanna know how many times operator / was called do it like this Code: #include <iostream> int divCount = 0; int main() { using namespace std; int n; cin >> n; cout << n << " = 1" ; for(int i = 2; i * i <=n ;++i) { while(n%i == 0) { cout << " * " << i; n /= i;// DIVISION HERE!!! INCREMENT DIVCOUNT ++divCount; } } if(n > 1) cout <<" * " << n; cout << endl << divCount << endl; cin.get(); } You may rightfully think that % is also division, and you might wanna count them too. Like this Code: #include <iostream> int divCount = 0; int main() { using namespace std; int n; cin >> n; cout << n << " = 1" ; for(int i = 2; i * i <=n ;++i) { int rem = n%i; //DIVISION HERE INCREMENT divCount; ++divCount; while(rem == 0) { cout << " * " << i; n /= i;// DIVISION HERE!!! INCREMENT DIVCOUNT ++divCount; rem = n%i; //DIVISION HERE INCREMENT divCount; ++divCount; } } if(n > 1) cout <<" * " << n; cout << endl <<divCount << endl; cin.get(); } Hope this helped Best Regards
Code: #include <iostream> using namespace std; int numOfDiv; void dec2oct(int n) { int leastSig=0; int mostSig=0; leastSig=n%8; ++numOfDiv; mostSig=n/8; ++numOfDiv; if(mostSig>7){ dec2oct(mostSig); } else{ cout<<mostSig; } cout<<leastSig; } int main(){ int num = 35; cout<< numOfDiv << endl; cout << oct << num << endl; cout << dec; dec2oct(num); int x; cin>>x; return 0; } it never counts, I just get a return output of 0. Is there something I am missing?
You are outputting that variable before increment and then the program ends. Variables do not have persistency i.e. store values across runs.
instead of the final int x; cin >> x; write just Code: cin.get(); Also, move the line Code: cout<< numOfDiv << endl; after the line Code: dec2oct(num); And everything will be fine