C++ program to generate Collatz Conjecture sequence.

// © 2017 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net

#include <iostream>

using namespace std;

unsigned long long collatzConjecture(unsigned long long num);

int main(){
  unsigned long long number;
  unsigned long long iterNum = 0;
  
  cout << "Enter a number: ";
  cin >> number;
  
  cout << number << " ";
  
  while(number != 1){
    number = collatzConjecture(number);
    cout << number << " ";
    
    iterNum++;
  }
  
  cout << endl << "It took " << iterNum << " iterations to reach 1" << endl;
  
  return 0;
}

unsigned long long collatzConjecture(unsigned long long num){
  if(num % 2 == 0){
    return num / 2;
  }else{
    return 3 * num + 1;
  }
}

 

C++ Collatz Conjecture Sequence Generator
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

This website stores some user agent data. These data are used to provide a more personalized experience and to track your whereabouts around our website in compliance with the European General Data Protection Regulation. If you decide to opt-out of any future tracking, a cookie will be set up in your browser to remember this choice for one year. I Agree, Deny
504