不知造成逾時瓶頸在哪裡?求最大公因數函式有從遞迴版修改成迴圈版但仍然逾時...
感謝~
/////////////////程式碼如下//////////////////
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
long long int C[10001]= {0};
long long int D[10001]= {0};
long long int gcd(long long int,long long int);
int main() {
int T = 0,N = 0,i = 0,j = 0;
while(scanf("%d",&T)==1) {
while(T--) {
memset(C,0,sizeof(C));
memset(D,0,sizeof(D));
scanf("%d",&N);
for(i = 0; i<N; ++i) {
scanf("%I64d",&C[i]);
}
if(N==2) {
printf("%I64d\n",D[0] = abs(C[1]-C[0]));
continue;
}
if(N==3) {
printf("%I64d\n",D[0] = gcd(abs(C[1]-C[0]),abs(C[1]-C[2])));
continue;
}
for(j=0; j<N-1; ++j) {
D[j] = abs(C[j]-C[j+1]);
}
--N;
while(N>=2) {
if(N==2) {
D[0] = gcd(D[1],D[0]);
break;
}
for(j=0; j<N-1; j++) {
D[j] = gcd(D[j],D[j+1]);
}
--N;
};
printf("%I64d\n",D[0]);
}
}
return 0;
}
long long int gcd(long long int p,long long int q) {
long int t =0;
while (q != 0) {
t =p % q;
p = q;
q = t;
}
return p;
}
你的程式中
while(N>=2) {
if(N==2) {
D[0] = gcd(D[1],D[0]);
break;
}
for(j=0; j<N-1; j++) {
D[j] = gcd(D[j],D[j+1]);
}
--N;
};
你的程式中,這個程式碼的時間複雜度是n^2(應該吧) 太高了...
當n=10000 必定會產生TLE
我將你的code 進行修改並貼在這裡
https://drive.google.com/file/d/0B-6m9awkIOO9Nm5BUWlnTnlTUms/view?usp=sharing