Prime fib numbers
I'm trying to write a program to output the first 5 prime Fibonacci numbers but for some reason it's printing out numbers that aren't prime
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int n)
{
/*
if ( n == 2) return true;
if (n <=1) return false;
if(n % 2 == 0 || n % 5 == 0)
return false;
if ( n % 2 == 1) return true;
*/
/*
if (n < 2) return false;
if (n % 2 == 0) return n ==2;
for (int i = 2; i <= sqrt (n); i +=2) {
if ((n%i) == 0) return false;
}
return true;
*/
int i,count=0;
if(n==1 || n==2)
return true;
if(n%2==0)
return false;
for(i=1;i<=n;i++)
{
if(n%i==0)
count++;
}
if(count==2)
return true;
else
return false;
}
int fib(int n) {
if(n == 1 || n == 2 || n == 0) return n;
if (n > 2)
{
return fib(n-1) + fib(n-2);
}
}
int main()
{
for(int i=1; i<=12; i++)
{
if (isPrime(i) == true)
{
cout << fib(i) << " ";
}
}
cout << endl;
return 0;
}
|
as you can see I've tried multiple different itsPrime functions but none of them are working
Last edited on
Are you trying to print out numbers that are both prime and Fibonacci numbers?
What your code is doing, at the moment, is that it's testing if
i
is a prime number and printing the i
th Fibonacci number.
I've modified your code to demonstrate this.
1 2 3 4 5 6
|
cout << "i" << "\t" << "fib(i)" << "\n";
for(int i = 1; i <= 12; i++)
{
if (isPrime(i) == true)
cout << i << "\t" << fib(i) << "\n";
}
|
i fib(i)
1 1
2 2
3 3
5 8
7 21
11 144
|
It looks like your
isPrime()
function is working as intended and the program is running as you directed it.
Last edited on
Yeah I'm trying to print out the first 5 prime Fibonacci numbers as in "2, 3, 5, 13, 89"
Update: I got it thanks for pointing out it was printing the ith Fib number
Topic archived. No new replies allowed.