Фибоначчи начинается с двух чисел.
unsigned previous = 0;
unsigned current = 1;
Следующий член задается суммой.
unsigned next = previous + current;
Тогда мы можем сдвинуть все.
previous = current;
current = next;
Теперь вам просто нужно ввести цикл и проверить, нужно ли вам печатать или выходить из цикла.
#include <stdio.h>
/* **********
Fibonacci:
F[0] = 0
F[1] = 1
F[n] = F[n-2] + F[n-1]
********** */
int main(void) {
unsigned min = 5;
unsigned max = 13;
unsigned previous = 0;
if (previous >= min)
print("%u\n", current);
unsigned current = 1;
while (current <= max) {
if (current >= min)
printf("%u\n", current);
unsigned next = previous + current;
previous = current;
current = next;
}
return 0;
}
Но есть более простое решение.
#include <stdio.h>
/* **********
Fibonacci:
F[0] = 0
F[1] = 1
F[n] = F[n-2] + F[n-1]
If we don't print the first element, this is the same as
F[0] = 1
F[1] = 0
F[n] = F[n-2] + F[n-1]
Taking this approach simplifies the code.
********** */
int main(void) {
unsigned min = 5;
unsigned max = 13;
unsigned previous = 1;
unsigned current = 0;
while (current <= max) {
if (current >= min)
printf("%u\n", current);
unsigned next = previous + current;
previous = current;
current = next;
}
return 0;
}
Наконецоптимизированное решение с использованием функций, предоставляемых @ Omarito.
#include <math.h>
#include <stdio.h>
const double phi = (1 + sqrt(5)) / 2;
unsigned fib(unsigned n) {
return round(pow(phi, n) / sqrt(5));
}
unsigned reverse_fib(unsigned fn) {
return round(log(sqrt(5) * fn) / log(phi));
}
int main(void) {
unsigned min = 5;
unsigned max = 13;
unsigned previous;
unsigned current;
if (min == 0) {
previous = 1;
current = 0;
}
else if (min == 1) {
previous = 0;
current = 1;
}
else {
current = min;
previous = fib(reverse_fib(current)-1);
}
while (current <= max) {
printf("%u\n", current);
unsigned next = previous + current;
previous = current;
current = next;
}
return 0;
}