I am new to C but doing some exercises (online and run to see if test passed) so this exercise is as follow
Requirements:
- write a function with return type unsigned and parameter unsigned (must use this type) -need to be able to get (return) the nth Fibonacci number for example 89 element (if first 3 elements are 0, 1, 1 the 89 element is 1,100,087,778,366,101,931).
Problem:
- saw some answers of using "unsigned long long" but the requirements don't allow using that type. Also can't use external libraries lime GMP
Need help what can I do?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned Fibonacci(unsigned numElement);
int main()
{
unsigned element;
element = Fibonacci(89);
printf("%d\n",element);
return 0;
}
unsigned Fibonacci(unsigned numElement){
int fibonacciArr[100] = {0, 1};
int i;
for(i = 2; i < numElement; i++ ){
fibonacciArr[i] = fibonacciArr[i-1] + fibonacciArr[i-2];
}
return fibonacciArr[numElement -1];
}
Get output:-2092787285 (i understand is out of range for unsigned int so is negative but not sure what to do to fix this) Instead of expected out:1100087778366101931
-tried to use "unsigned long long" but don't fit exercise requirement -change from first element to 1 (instead of 0 and worked) but thank you all
Those requirements as you understand them are simply impossible, because, as you say, the correct result is too big for a 32-bit-unsigned-integer.
There are several ways to interpret the task you were given:
unsignedeverywhere, including yourint-array. Overflowing an unsigned type is valid C, Overflowing a signed type is undefined behaviour.