I have a Time Limit Exceeded error in C. How do I overcome it?

喜你入骨 提交于 2021-02-17 07:13:11

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!