Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(C++) Program to print all prime numbers in the a Fibonacci sequence

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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 << " ";
        }

    }
}

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading