Home > Net >  (C ) Program to print all prime numbers in the a Fibonacci sequence
(C ) Program to print all prime numbers in the a Fibonacci sequence

Time:12-15

can someone help me out? I've been trying to get this program to print and add all prime numbers in the Fibonacci Sequence below 1000. Just typing the regular Fibonacci code works fine and will list the numbers 1 - 987.

However, the moment I put in a prime number checker it all of a sudden stops at 5 (printing "1 1 2 3 5" which is technically correct since they all fall under what a prime is (though 1 doesn't count). However I'm looking to see ALL prime numbers from 1 - 987 in the sequence, and no matter what I do I can't seem to get it to work.

My code's down below, don't mind the lack of a main function, I'm making this function as a part of a bigger program, but it can stand on its own. Currently testing it by just calling it in the main function.

#include <iostream>

using namespace std;

void primethousand() {
    int fibo = 1;
    int nacci = 1;
    int fibonacci = 0;
    int fibosum = 0; //used to get the sum of all printed numbers later, once this issue is fixed.
    int pchk = 0; /*primecheck, used to check if a number is a prime or not. 1 means not prime, 0 means prime*/

    cout << "\nPrime Fibonacci #s under 1000: \n\n";

    for (int ctr = 1; fibonacci < 987; ctr  ) {

        if (ctr == 1) {
            cout << fibo << " ";
            continue;
        } else if (ctr == 2) {
            cout << nacci << " ";
            continue;
        }

        fibonacci = fibo   nacci;
        fibo = nacci;
        nacci = fibonacci;

        //cout << fibonacci << " ";
        for (int chr = 2; chr < fibonacci; chr  ) {
            if (fibonacci % chr == 0) {
                pchk = 1;
            }
        }

        if (pchk == 0) {
            cout << fibonacci << " ";
        }

    }
}

CodePudding user response:

It looks like once pchk is set to 1, you never set it back to zero, so further primes are never noticed..

  • Related