The 3n + 1 Problem

Algorithm:

  1. Start with an integer n.
  2. If n is even, divide by 2.
  3. If n is odd, multiply by 3 and add 1.
  4. Repeat the process with the new value of n, terminating when n = 1.

 3n + 1 algorithm

//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

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.