Hi guys
I have this small assignment to do about foo numbers
that I should implement using a recursive.
First of all, foo numbers don't exist
Problem statement:
We define the concept of a foo number as follows. 0 is a foo number. If i is a foo number then i+5, and i+7 are also foo numbers. Write a recursive method which will test if a given integer is a foo number.
My code:
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
|
#include <iostream>
using namespace std;
bool isFoo(int n);
void main(){
int n;
cout<<"Enter a number"<<endl;
cin>>n;
while(cin){
if(isFoo(n))
cout<<n<<" is a Foo number"<<endl;
else
cout<<n<<" is not a Foo number"<<endl;
cout<<"Enter a number"<<endl;
cin>>n;
}
}
bool isFoo(int n){
if(n == 0)
return true;
else if(n < 0)
return false;
else
return false || isFoo(n - 5) || isFoo(n - 7);
}
|
The idea of the question is that you return true if the number is a multiple of
5 or 7, but I should implement it using recursive function.
The code works for both multiples of 5 and 7 but there's a logical
error that I can't figure out when you enter 12 it prints 12 is a Foo number
because at a certain case when the isFoo(n-5) returns, the value of n will be
7 and isFoo(n-7) will be true;
I can't find a way to do each term individually
I mean I want to find a way
that I keep subtracting the number by 5 untill we get either zero or negative
if it's zero then it's a foo number otherwise
keep subtracting the number by 7 untill
we get either zero or negative
if it's zero then it's a foo number otherwise it's not
do anybody have an idea for solving this problem
I'm new at recursion and I will be grateful for your help