This is the so-called 3x+1 problem, and I am trying to write a c++ program for it!
It's pseudocode from http://en.wikipedia.org/wiki/Collatz_con...
function collatz(n)
while n %26gt; 1
show n
if n is odd
set n to 3n + 1
else
set n to n / 2
show n
The program should stop when the sequence reaches 1
I will appreciate any help!
C++ program about Collatz conjecture?
How's this?
#include %26lt;iostream%26gt;
using namespace std;
int main()
{
int n;
cout %26lt;%26lt; "n=? ";
cin %26gt;%26gt; n;
while (n %26gt; 1)
{
cout %26lt;%26lt; n %26lt;%26lt; "\n";
if (n % 2 == 1)
n = 3*n + 1;
else
n = n / 2;
}
cout %26lt;%26lt; n %26lt;%26lt; "\n";
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment