The Hailstone Sequence – Solution

My solution to this month’s Exercise is split into two main parts. The first part generates the random value in the range of 1 to 100. The second part performs the Hailstone sequence on that value.

For the second part of my solution, I use a while loop, which spins until the value equals 1 — the end of the Hailstone sequence. As the loop spins, a test is made to determine if the value is odd. If so, the (n*3)+1 calculation is made, otherwise the value is divided by two. For each iteration, a length counter tracks the values generated.

Here’s the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int starting,length;

    /* initialize starting value */
    srand( (unsigned)time(NULL) );
    starting = (rand() % 100) + 1;
    length = 1;

    printf("Sequence: %3d ",starting);
    while(starting != 1)
    {
        if( starting % 2 )  /* true if odd */
            starting = (starting*3)+1;
        else                /* even */
            starting /= 2;
        printf("%3d ",starting);
        length++;
    }
    printf("\nSequence length: %d\n",length);

    return(0);
}

Line 11 generates the random number in the range of 1 to 100, saving the value in the starting variable.

The length variable is initialized at Line 12. It’s set to 1 because the starting value could be 1, in which case the length is 1. One and done.

The while loop begins at Line 15. If the starting value isn’t equal to 1, the loop repeats.

At Line 17 a test is made to determine whether the value is odd; the remainder of the mod 2 operation is 1 or TRUE when the value of starting is odd. Line 18 performs the odd calculation, resetting the value of variable starting.

If the value isn’t odd (meaning that it’s even), Line 20 divides starting by two.

The value of length is incremented at Line 22, and the loop repeats.

Most programming puzzles involving the Hailstone sequence do more than simply display and count individual values. For example, your code could run on all values in a range, say 1 to 100, and report which number has the longest or shortest Hailstone sequence in that range. Feel free to attempt that exercise on your own.

Leave a Reply