The 3n + 1 Problem
Tagged:
Algorithm:
- Start with an integer n.
- If n is even, divide by 2.
- If n is odd, multiply by 3 and add 1.
- Repeat the process with the new value of n, terminating when n = 1.

//3n + 1 problem
#include <stdio.h> int main(){ int num; //first number
int ans; //answer
int ctr; //counter
//the first number in the series
printf("enter integer n: "); scanf("%i", &num); ans = num; if(ans > 0){ printf("\t%i\n", ans); ctr = 1; while(ans > 1){ if(ans % 2 == 0) ans = ans / 2; else ans = ans * 3 + 1; printf("\t%i\n", ans); ctr ++; } printf("cycle length: %i", ctr); } else printf("positive integer only"); return 0; }

Post new comment