Home>

### c language fibonacci application without recursion

I am a beginner who has just started c language.
I am writing a program about a modified version of the Fibonacci sequence.
The problem is as follows.

The sequence f (n)
f (0) = 3, f (1) = 0, f (2) = 2, f (n) = f (n-2) + f (n-3) (n>2)
Is defined as.
n>1Andf (n) is divisible by nOf the integer n like32ndLet k be a small n.
Output the values ​​of k and f (k).

ex. The eighth smallest n is 19, f (19) = 209.

I wanted to use a recursive function for this problem, but I found it inefficient, so I wrote the corresponding source code (shown below) without using recursion. However, the output obtained (listed below) is clearly incorrect (n is negative).
If anyone knows the cause, please teach me.

Corresponding source code
``````#include<stdio.h>
#define TARGET 32
int main () {
long f0 = 3, f1 = 0, f2 = 2, fn;
int n, cnt = 1;// When n = 2, set cnt to 1 in advance because the condition is satisfied with f (2) = 2.
for (n = 3 ;;n ++) {
fn = f1 + f0;
if (fn% n == 0) cnt ++;
if (cnt>= TARGET) {
printf ("% d% ld \ n", n, fn);
break;
}
f0 = f1;
f1 = f2;
f2 = fn;
}
return 0;
}``````
Obtained output

-27355683 1231005735

What I tried

If i change TARGET to 8 and execute it, it will be output as 19 209 as ex.

Supplementary information (FW/tool version, etc.)

Compile with gcc.