Write a complete C++ program that does the following: 1. The program will contai
ID: 648832 • Letter: W
Question
Write a complete C++ program that does the following:
1. The program will contain 4 functions:
a. Function Fibonacci(int n) calculates the nth Fibonacci number
b. Function isPrime(int n) checks if n is a prime number.
c. Function number(int n) that prints the numbers in sequential order based on number passed in. For example if n = 6, the output would be 123456.
d. Function spaces(int n) that prints the n copies of spaces
2. The main program should utilize the Fibonacci(int n) and isPrime(int n) to print out the first 6 Fibonacci numbers that are also prime.
3. The main program should call the spaces and number function to create the diagram of below.
Diagram 1 Diagram 2 Diagram 3 Diagram 4
1 12345 1 12345
12 1234 123 1234
123 123 12345 123
1234 12 1234567 12
12345 1 123456789 1
Explanation / Answer
#include <iostream>
using namespace std;
void number(int number);
int Fibonacci(int n);
bool isPrime(int number);
int main()
{
cout<<"please enter number";
int n;
cin>>n;
number(n);//enter 15 as input
return 0;
}
int Fibonacci(int n)
{
if (n == 0 || n == 1)
return n;
else
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
bool isPrime(int number){
if(number < 2) return false;
if(number == 2) return true;
if(number % 2 == 0) return false;
for(int i=3; (i*i)<=number; i+=2){
if(number % i == 0 ) return false;
}
return true;
}
void number(int number){
for(int i=1;i<=number;i++){
int fib = Fibonacci(i);
if(isPrime(fib)){
cout<<"number is"<<fib<<" ";
}
}
}
void spaces(int number){
for(int i=1;i<=number;i++){
cout<<" ";
}
}
2)
#include <iostream>
using namespace std;
void number(int number);
int main()
{
while(true){
int number;
cout<<"1)pattern-1 2)pattern2 3)pattern 3 4)exit";
cin>>number;
if(number==1){
pattern1();
}
else if(number==2){
pattern2();
}
else if(number==3){
pattern3();
}
else if(number==4){
break;
}
}
return 0;
}
void pattern1(){
int i,j;
for(i=1;i<=5;++i)
{
for(j=1;j<=i;++j)
{
cout<<j<<" ";
}
cout<<" ";
}
}
void pattern2(){
int i,j;
for(i=5;i>=1;--i)
{
for(j=1;j<=i;++j)
{
cout<<j<<" ";
}
cout<<" ";
}
}
void pattern3(){
int b=1,i,k,space;
for(i=1;i<=5;++i)
{
for(space=1;space<=5-i;++space)
{
cout<<" ";
}
b=1;
while(k!=2*i-1)
{
cout<<b;
b++;
++k;
}
k=0;
cout<<" ";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.