Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Next(n) returns the number that follows n in a hailstone sequence.
- // For example, next(7) = 22 and next(8) = 4.
- //
- // Next requires n > 1, since there is no number that follows 1.
- int next(int n)
- { if(n > 1)
- {
- if((n%2)==0)
- {
- n = n/2;
- }
- else
- {
- n = 3*n+1;
- }
- }
- return n;
- }
- //writeHailstoneSequence returns the
- void writeHailstoneSequence(int n)
- {
- int m = n;
- if(m == 1)
- {
- printf("%i", m);
- }
- else
- {
- printf("%i ", m);
- writeHailstoneSequence(next(n));
- }
- }
- //reads int n from the 'next' function
- //counts every time we calculate in
- //'next' and returns that value
- int lengthHailstone(int n)
- {
- int l = n;
- if(l == 1)
- {
- return 1;
- }
- else
- {
- return lengthHailstone(next(n))+1;
- }
- }
- //calculates every int n and compares
- //it to the int largestValue and if n
- //is larger then largestValue takes
- //same value as n
- int largestHailstoneValue(int n)
- {
- int v = n;
- if(v == 1)
- {
- return 1;
- }
- else
- {
- return max(largestHailstoneValue(next(n)), v);
- }
- }
- //if int n is 1 then returns 1
- //calculates the longest length
- //seqeunce from 1 to n
- int longestLength(int n)
- {
- if(n > 1)
- {
- return max(lengthHailstone(n), longestLength(n-1));
- }
- else
- {
- return 1;
- }
- }
- //uses lengthHailstone function to
- //compare each int up to int n to find
- //the first value of the longest sequence
- int firstValueBiggestSequence(int n)
- {
- int firstValue = 1;
- for(int i = 2; i <= n; i++)
- {
- if(lengthHailstone(i) > lengthHailstone(firstValue))
- firstValue = i;
- }
- return firstValue;
- }
- //uses largestHailstoneValue function
- //to find the largest value from 1
- // to n using a loop from i(1) to n
- int biggestOverallValue(int n)
- {
- int biggestValue = 0;
- for(int i = 1; i <= n; i++)
- {
- if(biggestValue < largestHailstoneValue(i))
- {
- biggestValue = largestHailstoneValue(i);
- }
- }
- return biggestValue;
- }
- int main()
- {
- int n;
- printf("What number shall I start with?\n");
- scanf("%i", &n);
- printf("The hailstone sequence starting at %i is: \n", n);
- writeHailstoneSequence(n);
- printf("\nThe length of the sequence is %i.\n", lengthHailstone(n));
- printf("The largest number in the sequence is %i.\n", largestHailstoneValue(n));
- printf("The longest hailstone sequence starting with a number up to ");
- printf("%i has length %i.\n", n, longestLength(n));
- printf("The longest hailstone sequence starting with a number up to ");
- printf("%i begins with %i.\n", n, firstValueBiggestSequence(n));
- printf("The largest value in any hailstone sequence starting with ");
- printf("a number up to %i is %i.\n", n, biggestOverallValue(n));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement