Post Reply 
 
Thread Rating:
  • 0 Votes - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
3x+1 problem
08-02-2009, 10:38 PM
Post: #1
3x+1 problem
I was looking through some of problems that i used to solve few years ago, and i came across an simple problem !
Consider the following algorithm to generate a sequence of numbers. Start with an integer n. If n is even, divide by 2. If n is odd, multiply by 3 and add 1. Repeat this process with the new value of n, terminating when n = 1. For example, the following sequence of numbers will be generated for n = 22:
Code:
22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured (but not yet proven) that this algorithm will terminate at n = 1 for every integer n. Still, the conjecture holds for all integers up to at least 1, 000, 000. For an input n, the cycle-length of n is the number of numbers generated up to and including the 1. In the example above, the cycle length of 22 is 16. So you need to find a number or cycle length !
This is solution is TPW :
Code:
program three_x_plus_one;
uses wincrt;
var
n,i:longint;
begin
writeln('Enter number !');
readln(n);
i:=1;
repeat
  begin
    if n mod 2 = 0 then
     n:=n div 2
     else
     n:=3*n+1;
     i:=i+1;
  end;
until n=1;
writeln('Solution is ',i);
end.
And for C++ coders :
Code:
# include <iostream>
# include <cstdio>

using namespace std;

int main()
{
    int i,n;
    cout<<"Enter number \n";
    cin>>n;
    i=1;
    while (n > 1)
    {
        if (n % 2 == 0)
         n=n/2;
         else
         n=3*n+1;
         i++;  
    }
    cout<<"Solution is "<<i<<"\n";\
    system("pause");
}

There's a fine line between genius and insanity. I have erased this line.
Oscar Levant
There's a fine line between an administrator and black hat hacker. I have erased this line.
Dr DEBCOL
Visit this user's website Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump:


 Quick Theme: