Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Guessing Prime and Fibonacci numbers (C++ program) Make a program that asks for

ID: 3671904 • Letter: G

Question

Guessing Prime and Fibonacci numbers (C++ program)

Make a program that asks for a number, then tells you if that number is a Fibonacci number and/or a prime number. You may assume only whole numbers are entered. We will also not test your code on numbers smaller than 3.

/////////////////////////////////////////////////////////

Example 1 (user input is underlined):

Give me a number, HUMAN: 5

That is (optimus) prime.

That is a Fibonacci.

//////////////////////////////////////////////////

Example 2 (user input is underlined):

Give me a number, HUMAN: 6

Explanation / Answer


    #include <iostream>
    using namespace std;
    #include<conio.h>
#include <math.h>

void checkPrime(int num)
{
      for(int i=2;i<=num/2;++i)
      {
          if(num%i==0)
          {
              flag=1;
              break;
          }
      }
      if (flag==0)
          cout<<"This is a Prime Number";
      else
          cout<<"This is not a Prime Number";
      getch();
}

bool isPerfectSquare(int x)
{
    int s = sqrt(x);
    return (s*s == x);
}

// Returns true if n is a Fibinacci Number, else false
bool isFibonacci(int n)
{
    // n is Fibinacci if one of 5*n*n + 4 or 5*n*n - 4 or both
    // is a perferct square
    return isPerfectSquare(5*n*n + 4) ||
           isPerfectSquare(5*n*n - 4);
}

    int main()
    {
      int num, i, flag=0;
      cout<<"Give me a number: ";
      cin>>num;
flag=checkPrime(num);


     isFibonacci(num)? cout << num << " is a Fibonacci Number ":
                     cout << num << " is a not Fibonacci Number " ;


//end of main
    }