问题
c performance profiling time-limiting Details of the purpose of writing the program is given on the link : https://www.spoj.com/problems/CRCLE_UI/
And the error Time limit exceeded
#include<stdio.h>
const int mod=1000000007;
int cal(int a, int b){
long long x=1,y=a;
while(b){
if(b&1)x=x*y;
if(x>=mod)x=x-(x/mod)*mod;
y=y*y;
if(y>=mod)y=y-(y/mod)*mod;
b>>=1;
}
return x;
}
int main(){
int t, n, k;
long long ans,a1;
for(scanf("%d",&t);t--;){
scanf("%d %d", &n, &k);;t--;
k--;
if(k>=mod)k%=mod;
ans=(long long)k;
if(n&1)ans=ans*(-1);
a1=cal((int)k,n);
printf("%lld\n",(a1+ans+mod)%mod);
}
}
回答1:
The problem is designed so that it is impossible to compute a result directly by exponentiating with n. Any such attempt will exceed the available resources. You must solve the problem using some number theory, particularly Fermat’s Little Theorem. Additionally, you cannot use scanf to process the input numerals but must read them yourself character by character and reduce them using number theory.
回答2:
Why the second t-- on this line?
scanf("%d %d", &n, &k);;t--;
Getting rid of it allows the program to halt for any value of t (even and odd, so long as they're positive). Remember, the for loop's condition, t--, tests if t is 0. If it's any non-zero value, it'll evaluate to true.
What your code did was essentially make it so that any odd-number entered as t will never evaluate to 0. Take 1 for example: it's scanned in, t-- in the for condition decrements it, the above line decrements it, so the next time the loop is evaluated t == -1, which evaluates to true. Every iteration after that will just be a more negative number, never 0.
来源:https://stackoverflow.com/questions/61811741/i-have-a-time-limit-exceeded-error-in-c-how-do-i-overcome-it