How to optimize Tom and Jerry code which passed for subtask?

I am using recursive approach , but failed to further optimize it. It is getting passed for subtask , how to improve the efficiency:

#include <bits/stdc++.h>
using namespace std;
void func(long JS,long TS,long &count){
    if(JS<1 || ( (JS&1) && (TS&1)))
    return;
    
    if((TS&1) && !(JS&1)){
        count++;
    }
    if(!(TS&1) && !(JS&1)){
        func(JS>>1,TS>>1,count);
    }
    return;
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
	int t;
	cin>>t;
	while(t--){
	    long TS,ans=0;
	    cin>>TS;
	    for(long i=1;i<=TS;i++){
	        long c=0;
	        func(i,TS,c);
	        ans+=c;
	    }
	    cout<<ans<<endl;
	}
	return 0;
}

Recursive approach won’t work due to large constraints.
Try a O(log n) or a O(1) solution.

Check out my submission:
https://www.codechef.com/viewsolution/34449739

Check out this video explanation>>>

As @zappelectro has mentioned, you have to try an O(logn) or an O(1) approach.
You can check my solution here for an O(1) approach.

1 Like

Fantastic +1

1 Like