Uploaded by Shreya Chinchmalatpure

3n+1

advertisement
3n+1 Problem
<Name: Shreya Chinchmalatpure>
<Roll.No: 348>
<PNR: 2046491245048>
<Date of Submission: 05-03-2023>
Problem Description
 3n+1 problem also known as Collatz conjecture/problem.
 To solve this problem we take any positive integer n. If n
is even, divide it by 2 i.e n / 2. If n is odd, multiply it by 3
and add 1 to obtain 3n + 1. Repeat the process until 1 is
obtained. The conjecture is that no matter what number
you start with, you will always eventually reach 1.
 For Example:
Consider n=12,
We get the sequence as  12, 6, 3, 10, 5, 16, 8, 4, 2, 1.
Proposed Solution
Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then n ← 3n + 1
5. else n ← n/2
6. GOTO 2
For any two numbers i and j you are to determine the
maximum cycle length over all numbers between and
including both i and j.
Uploaded Code
int main()
{
int a, b; //input vars
while (scanf("%d %d", &a, &b) != EOF)
{
printf("%d %d %d\n", a, b, maxCycleSizeBetween(a, b));
}
return 0;
}
int cycleSize(int x){
int cycle = 1;
while (x != 1){
if (x % 2 == 0){
x = x / 2;
} else
{ //if odd
x = x * 3 + 1; }
cycle++; }
return cycle;
}
int maxCycleSizeBetween(int a, int b)
{
if (a > b)
{ //if b > a, swap them
int temp = a;
a = b;
b = temp;
}
int maxCycle = 0;
while ( a <= b )
{
int thisCycleSize = cycleSize(a);
if (thisCycleSize > maxCycle)
{
maxCycle = thisCycleSize;
}
a++;
}
return maxCycle;
Screen shot of accepted solution
Download