Friday, October 14, 2011

Start with a positive integer n. If n is even, divide it by 2, else replace n by 3n+1. Repeat until we obtain the value 1 in the sequence. The 3x+1 conjecture says that we eventually reach 1 irrespective of what initial value of n we start with. Different initial values of n lead to different numbers of iterations of the loop before hitting the value 1. For example, if we start with n=3, we get a sequence 3,10,5,16,8,4,2,1 using 7 iterations. If we start with 7, we need 16 iterations, since the sequence is now 7,22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1. You are given a bound B. Your task is to locate that particular value of n in the range 1<=n<=B for which the number of iterations is maximum. Once this integer nis located, you print n, the corresponding number of iterations, and finally the sequence associated with n. If the bound is 10, then the output of your program would look like: Maximum number of iterations = 19 for n = 9. The sequence is: 9 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 Report the output of your program for the bound 100,000.

#include
main()
{
int a,b,c,d,e,f=0,g=0,h=0;
printf("Enter your Bound :\t");
scanf("%d",&a);
for(b=1;b<=a;b++)
{
c=b;
f=0;
d=b;
while(c!=1)
{
if(c%2==0)
{
c=c/2;
f=f+1;
}
else
{
c=(3*c)+1;
f=f+1;
}
}
if(g {
g=f;
e=d;
}
}
printf("Maximum number of iterations = %d for n=%d\n",g,e);
printf("The sequence is : %d\n",e);
while(e!=1)
{
if(e%2==0)
{
e=e/2;
h=h+1;
printf("%d ",e);
}
else
{
e=(3*e)+1;
h=h+1;
printf("%d ",e);
}
}
printf("\n");
}

No comments:

Post a Comment