用c语言写出ackermenn非递归算法
时间: 2024-09-12 16:07:23 浏览: 41
Akerman's non-recursive algorithm是一种用于计算Fibonacci数列的方法,它避免了直接的递归调用,而是通过循环迭代的方式实现。以下是C语言中使用Akerman方法计算Fibonacci数列的一个简单版本:
```c
#include <stdio.h>
// Akerman's non-recursive Fibonacci function
unsigned long long fibonacci(int n) {
if (n <= 0)
return 0;
else if (n == 1)
return 1;
unsigned long long fib_n = 1, fib_n_minus_2 = 0, fib_n_minus_1 = 1;
for (int i = 2; i < n; ++i) {
unsigned long long temp = fib_n;
fib_n = fib_n + fib_n_minus_2;
fib_n_minus_2 = temp;
}
return fib_n;
}
int main() {
int num;
printf("Enter a number to calculate its Fibonacci: ");
scanf("%d", &num);
// Check for valid input range
if (num < 0) {
printf("Invalid input! Fibonacci series is not defined for negative numbers.\n");
return 0;
}
unsigned long long result = fibonacci(num);
printf("The %dth Fibonacci number is: %llu\n", num, result);
// Related questions:
阅读全文