C/C++, Codes

Hailstones Sequence

HailStones is a sequence of number that is generated by the following rule:
For a number X_{n} the next number is 3*X_{n} + 1 if X_{n} is odd.
Otherwise, it will be X_{n}/2.
Lothar Collatz in 1937 proposed that the sequence will eventually reach 1. Well it is not yet proved yet^^.

Language implementation : C++.

/**

  @author : HoDuc

  @Goal   : Calculate HailStone number Xn = Xn/2 (Xn even) or Xn = 3Xn + 1(Xn odd)

  @Date   : 02/18/2012

 */

#include <iostream>

using namespace std;

//print out the hailstone sequence

void hailstones(int);

int main()

{

	int n;

	cout << "Enter a number: ";

	cin  >> n;

	hailstones(n);

	return 0;

}


void hailstones(int n)

{

	cout << "Look at the hailstones pattern:";

	cout << n << " ";

	//because hailstone sequence will eventually collapse to 1

	//it is a yet proved conjecture.

	while (n != 1)

	{
		((n % 2) == 0) ? (n = n / 2) : (n = 3*n + 1);
		cout << n << " "; 

	}

	cout << endl;

}

Sample run :

Enter a number : 13
Look at the hailstones pattern:13 40 20 10 5 16 8 4 2 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s