I was trying to attempt a simple question on HackerEarth. I code in python usually. My test cases were failing due to time limit in python so I tried to implement the same logic via C programming. And in C it just completed in 0.7 seconds. Mostly the login implementation is same. If its due to input size, could you please suggest something that I should use in python to get similar time as that of C.
The question is not duplicate one as here time taken vastly differs with C so all I am asking is better approach to rewrite the python code which is memory efficient.
Here's my code in python:
for _ in range(int(input())):
n=int(input())
c=0
for i in range(1,n):
for j in range(i+1,n+1):
if(j>n):
break
if((i^j) <= n):
c+=1
print(f'{c}')
Here's my code in C:
#include <stdio.h>
int main(){
int n,c,t,k,i,j;
scanf("%d",&t);
for(k=0;k<t;k++){
c=0;
scanf("%d",&n);
for(i=1;i<n;i++){
for(j=i+1;j<n+1;j++){
if(j>n){
break;
}
if((i^j) <= n){
c+=1;
}
}
}
printf("%d\n",c);
}
}
I am not asking anyone to solve any question here. I already solved the question using 2 programming languages I just to know why similar logic taking very long time and eventually failing due to time constraint in python. And how can I avoid this in future. I don't wanna code in C anymore as I totally forgot it and python is obviously easy to implement.