Skip to main content

nth Fibonacci term prime check

Short answer

Generate the nth Fibonacci number (starting 0,1) iteratively by updating a and b. Check primality by trial division up to square root. For input n=8, the Fibonacci term is 13, which is prime. For n=7, term 8 is not prime.

Write a program in C to find out whether the nth term of the Fibonacci series is a prime number or not. Read the value of n from the user and display the result in the main function. Use separate user-defined functions to generate the nth Fibonacci term and to check whether a number is prime or not.

The Fibonacci series is 0, 1, 1, 2, 3, 5, 8, 13, 21, ... with each term the sum of the previous two. The function fib(n) returns the nth term (term 1 = 0, term 2 = 1). The function isprime() returns 1 when a number is prime. main() reads n, calls both functions and displays the result.

#include <stdio.h>
long fib(int n)
{
    long a = 0, b = 1, t;
    int i;
    if (n == 1) return 0;
    if (n == 2) return 1;
    for (i = 3; i <= n; i++)
    {
        t = a + b;
        a = b;
        b = t;
    }
    return b;
}
int isprime(long x)
{
    long i;
    if (x < 2) return 0;
    for (i = 2; i * i <= x; i++)
        if (x % i == 0)
            return 0;
    return 1;
}
int main(void)
{
    int n;
    long f;
    printf("Enter n: ");
    scanf("%d", &n);
    f = fib(n);
    printf("Term %d of the Fibonacci series = %ld\n", n, f);
    if (isprime(f))
        printf("%ld is a prime number\n", f);
    else
        printf("%ld is not a prime number\n", f);
    return 0;
}

Output for n = 7:

Enter n: Term 7 of the Fibonacci series = 8
8 is not a prime number

Output for n = 8: Term 8 of the Fibonacci series = 13 and 13 is a prime number.

Explanation

  • fib() keeps the last two terms in a and b and moves forward with t = a + b.
  • isprime() rejects numbers below 2 and tests divisors from 2 up to √x.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 6 questions →