So there are two function that I don't know how to write for this program. The first one would take an integer n and return the length of the longest hailstone longest hailstone sequence starting at a number from 1 to n.
The second function I don't know how to write is meant to take an integer n and return the start value of the longest hailstone sequence that starts on a value from 1 to n. How do I go about writing these? here is my code so far.
#include <cstdio>
using namespace std;
// The function next(n)takes an integer value n and
// returns the number that follows n in a hailstone sequence.
// For example: next(7) = 22 and next(22) = 11.
int next(int n)
{
if (n == 1)
{
return n;
}
else if (n%2==0)
{
return n=n/2;
}
else
{
return n=3*n+1;
}
}
// The function hailstone reads int n and
// prints its entire hailstone sequence.
// Parameters: int n. Uses next() function.
void sequence(int n)
{
printf("%i ",n);
if(n!=1)
{
n=next(n);
sequence(n);
}
}
// Parameters: int length, int n
// Uses next function, to calculate the length of the sequence.
int length(int n)
{
int length = 1;
while (n > 1)
{
n = next(n);
++length;
}
return length;
}
int largest(int n)
{
if(n==1)
{
return 1;
}
int maxint = largest(next(n));
return maxint>n? maxint:n;
}
int main()
{
int n;
printf("What number shall I start with? ");
scanf("%i", &n);
printf("The hailstone sequence starting at %i is:", n);
sequence(n);
printf("\nThe length of the sequence is: %i", length(n));
printf("\nThe largest number in the sequence is: %i", largest(n));
printf("\nThe longest hailstone sequence starting with a number ");
printf("up to %i has length %i",n, length(n));
printf("\nThe longest hailstone sequence starting with a number ");
printf("up to %i begins with %i\n",n,n);
return 0;
}
Aucun commentaire:
Enregistrer un commentaire