[英]SPOJ same algorithm accepted in C, Time limit Exceeded in Python
I am trying to solve the FCTRL problem from SPOJ. 我试图从SPOJ解决FCTRL问题。 The problem is to find the number of trailing zeroes in N!
问题是在N中找到尾随零的数量! for some T test cases.
对于一些T测试用例。
T ~ 1,00,000.
1 <= N <= 1000000000
My problem is very strange. 我的问题很奇怪。 If I try the following C code, it gets accepted with time 0.22 seconds and a memory usage of 1.6M.
如果我尝试以下C代码,它会被接受,时间为0.22秒,内存使用量为1.6M。 But if I submit the equivalent Python 3 code, it says Time Limit Exceeded with memory usage of 11M.
但是,如果我提交等效的Python 3代码,它会说超出时间限制,内存使用量为11M。
C Code: C代码:
#include <stdio.h>
void fact_zeros(long int);
int main(void) {
long int i,t,n;
if (scanf("%ld",&t) > 0) {
for (i=1;i<=t;i++) {
if (scanf("%ld",&n) > 0) {
fact_zeros(n);
}
}
}
return 0;
}
void fact_zeros(long int N) {
long int zeros = 0;
while (N>0) {
N = N / 5;
zeros += N;
}
printf("%ld\n",zeros);
}
Python 3 Code: Python 3代码:
"""
spoj11Factorial.py
This program calculates the number of zeroes at the
end of the factorial of each number of the test case.
"""
def fact_zeroes( n ):
count_5s = 0
while (n > 0):
n = n // 5
count_5s += n
return count_5s
T = int( input() )
while (T):
T -= 1
n = int( input() )
zeroes = fact_zeroes( n )
print( zeroes )
Can anyone please spot what different / wrong I am doing in the Python code. 任何人都可以在Python代码中发现我正在做的不同/错误。 It works for all given test cases on my machine.
它适用于我机器上的所有给定测试用例。
Thanks. 谢谢。
EDIT: Problem Specifications: 编辑:问题规格:
Added by: Adrian Kosowski
Date: 2004-05-09
Time limit: 6s
Source limit: 50000B
Memory limit: 256MB
Cluster: Pyramid (Intel Pentium III 733 MHz)
Languages: All except: NODEJS PERL 6
Resource: ACM Central European Programming Contest, Prague 2000
One very easy way to more than double the speed of this program is to convert: 将此程序的速度提高一倍以上的一种非常简单的方法是转换:
n = int( input() )
to 至
n = int( raw_input() )
Note that raw_input() returns a string from the input, while input() runs the Python interpreter on the string after reading it. 请注意, raw_input()从输入中返回一个字符串,而input()在读取后在字符串上运行Python解释器。
On my computer using Python 2.7 this reduces the time from 1.6 seconds to 0.7 seconds 在使用Python 2.7的计算机上,这将时间从1.6秒减少到0.7秒
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.