So if I write out a collatz sequence of the given number long int n in my first function then in the next I wanna return the biggest number how do I do take for example if I call the first writeCollatzSekvens(7) it writes out 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1 and I wanna return 52.
void writeCollatzSekvens(long int n){
cout << n << " ";
while(n !=1){
if ( n % 2 == 0){
n = n/2;
cout << n << " ";
}
else{
n = (n*3) + 1;
cout << n << " ";
}
}
}
long int collatzMax(long int n){
int max = 0;
if (n > max){
max = n;
}
return max;
}
You have the following problem in your "collatzMax"-function:
Your function is stateless. It does not remember the "old" max value. This will not work. It is anyway not called in your other function. And there it is needed.
If you want to have the max collatz number, then you need to calculate max-values in your main loop.
And, if you have calculated your max number in the main loop, you can return it at the end of the function.
This could then for example look like that:
Of course there are many other potential solutions
EDIT
If the function should be void, then we can add an additional output parameter maxNumber. And pass this parameter by reference or by pointer.
Please see the example below. using pointer:
Using reference