Class assignment

whats wrong in my code

#include
using namespace std;
void class1(int n,string s,int &ans){
if(n==0){

 ans++;
 return;

}
if(n<0){
return;
}
class1(n-1,“a”+s,ans);
int x=s.length();

 if(s[x-1]!='b'){
	 class1(n-1,"b"+s,ans);
 }

}
int main() {
int t;
cin>>t;
while(t–){
int n;
cin>>n;
int cnt=0;
class1(n,"",cnt);
cout<<"#"<<n<<" : "<<cnt<<endl;
}
return 0;
}

Hello @kumarakash121005,

I have implemented the correct logic for you, you can check out here.

why this is wrong
and this code is same as fibonacci

@kumarakash121005,

Your implementation is wrong, for example:

N = 6
1
2
3
4
5
6

Your code’s output:

#1 : 2
#2 : 3
#3 : 5
#4 : 9
#5 : 17
#6 : 33

Clearly, it doesn’t match with the Fibonacci sequence i.e.( 2, 3, 5, 8, 13, 21…)

@kumarakash121005,

Also while printing the answer, you need to print the current test case number instead of n.

cout<<"#"<<testcase_number<<" : "<<answer<<endl;

hum y kaise sure h ki hmari series fibonnaci hi h

@kumarakash121005,

Recursion cases:

  1. If the current element is a then, it is sure that the previous element could be anything either a or b.
    Total ways = f(n-1)

  2. If the current element is b then, it is not possible for the previous element to be b as consecutive elements can’t be equal to b. So, we are left with only 1 case where the previous element = a and, the sequence looks like this:

…ab
Total ways = f(n-2)

F(n) = if current element is a + if current element is b
= f(n-1) + f(n-2)

but this recursion case is similar to Fibonacci.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.