prime fibonacci number code example

Example: fibonaci primes

#include <iostream>

int main() {
    std::cout << "Enter a positive integer:\n";

    unsigned int m;
    std::cin >> m;

    // try all fibonacci numbers
    unsigned int prev_n = 1;
    unsigned int count = 0;

    for (unsigned int n = 2; n <= m;) {
        
        // test if n is prime
        unsigned int d;
        for (d = 2; n % d != 0; ++d);

        if (d == n) {
            // found fibonacci prime
            std::cout << n << "\n";
            ++count;
        }

        // compute next fibonacci number
        unsigned int next_n = n + prev_n;
        prev_n = n;
        n = next_n;
    }

    std::cout << "Found " << count << " fibonacci primes\n";
        
    return 0;
}

Tags:

Misc Example