Consider the following sequence defined by:
\[ U_0=1 ; U_n= \Big\{\begin{array}{c c c} U_{n-1}^2 & if & \texttt{n is an even number } \\ U_{n-1}+n! & if & \texttt{n is an odd number} \end{array}\]
- Write a function that takes an integer n as parameter, and returns the corresponding value of $$U_n$$.
- Write a function that takes as parameter an integer X, and prints the greatest value of n such that $$U_n \leq X$$
Difficulty level
This exercise is mostly suitable for students
#include <stdio.h>
#include <math.h>
int fact(int n)
{
if(n==0) return 1;
return n * fact(n-1);
}
int sequence(int n)
{
if(n==0) return 1;
if(n%2) return sequence(n-1)+fact(n);
return pow(sequence(n-1),2);
}
int closest(int x)
{
int i=1;
while(sequence(i)<x)
i++;
return i-1;
}
int main()
{
printf("sequence(4)=%d\n",sequence(4));
printf("sequence(5)=%d\n",sequence(5));
printf("closest(230)=%d\n",closest(230));
return 0;
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
Binary search trees in levels