我的解决方案非常快但不够。我需要更快。我怎样才能减少时间? 输入数量:n(0≤n≤1000000) 基数应为:碱(2≤碱≤1000)
时间限制:2秒(秒)和内存限制:32 MB
这是我用c语言编写的代码:
#include<stdio.h>
#include<math.h>
int factorialDigitExtended ( int n, int base ) {
double x = 0;
for ( int i = 1; i <= n; i++ ) {
x += log10 ( i ) / log10(base);
}
int res = ( (int) x ) + 1;
return res;
}
int main(){
int i, t, n, b;
for(i=1; i<= t; i++){
scanf("%d %d", &n, &b);
printf("Case %d: %d\n", i, factorialDigitExtended(n, b));
}
return 0;
}
答案 0 :(得分:1)
就像我在上面的评论中提到的那样,这可能是针对特定目标的行为。我会看一些事情:
只计算一次常数值:
int factorialDigitExtended ( int n, int base ) {
double x = 0;
double lbase = log10(base);
for ( int i = 1; i <= n; i++ ) {
x += log10 ( i ) / lbase;
}
int res = ( (int) x ) + 1;
return res;
}
分部可能很贵:
int factorialDigitExtended ( int n, int base ) {
double x = 0;
double lbase = 1 / log10(base);
for ( int i = 1; i <= n; i++ ) {
x += log10 ( i ) * lbase;
}
int res = ( (int) x ) + 1;
return res;
}
不要重复相同的乘法n次:
int factorialDigitExtended ( int n, int base ) {
double x = 0;
double lbase = 1 / log10(base);
for ( int i = 1; i <= n; i++ ) {
x += log10 ( i );
}
x *= lbase;
int res = ( (int) x ) + 1;
return res;
}
0比较可能更便宜:
int factorialDigitExtended ( int n, int base ) {
double x = 0;
double lbase = 1 / log10(base);
for ( int i = n; i > 0; --i ) {
x += log10 ( i );
}
x *= lbase;
int res = ( (int) x ) + 1;
return res;
}
由于精度问题,Btw(int)x可能会在某些点失败。
可能还有处理器特定的对数指令。