【发布时间】:2015-04-28 04:23:50
【问题描述】:
以下代码是一种算法,用于确定具有整数中位数的最大边小于或等于 MAX 的整数三角形的数量。 Python 版本可以工作,但对于更大的 N 来说太慢了,而 C++ 版本要快很多,但没有给出正确的结果。
当 MAX 为 10 时,C++ 和 Python 都返回 3。
当 MAX 为 100 时,Python 返回 835,C++ 返回 836。
当 MAX 为 200 时,Python 返回 4088,C++ 返回 4102。
当 MAX 为 500 时,Python 返回 32251,C++ 返回 32296。
当 MAX 为 1000 时,Python 返回 149869,C++ 返回 150002。
这是 C++ 版本:
#include <cstdio>
#include <math.h>
const int MAX = 1000;
int main()
{
long long int x = 0;
for (int b = MAX; b > 4; b--)
{
printf("%lld\n", b);
for (int a = b; a > 4; a -= 2){
for (int c = floor(b/2); c < floor(MAX/2); c+=1)
{
if (a+b > 2*c){
int d = 2*(pow(a,2)+pow(b,2)-2*pow(c,2));
if (sqrt(d)/2==floor(sqrt(d)/2))
x+=1;
}
}
}
}
printf("Done: ");
printf("%lld\n", x);
}
这是原始 Python 版本:
import math
def sumofSquares(n):
f = 0
for b in range(n,4,-1):
print(b)
for a in range(b,4,-2):
for C in range(math.ceil(b/2),n//2+1):
if a+b>2*C:
D = 2*(a**2+b**2-2*C**2)
if (math.sqrt(D)/2).is_integer():
f += 1
return f
a = int(input())
print(sumofSquares(a))
print('Done')
我对 C++ 不太熟悉,所以我不知道是什么原因导致了这种情况(可能是溢出错误?)。
当然,我们非常欢迎对算法进行任何优化!
【问题讨论】:
-
首先,C++ 版本使用
floor,而python 使用ceil。此外,C++ 版本不除以 2if (sqrt(d)==floor(sqrt(d)))而 python 版本是if (math.sqrt(2*D)/2).is_integer(): -
python 版本给我
4输入10。 -
它们都有乘以 2(只是在不同的地方),但只有 Python 的在平方根之后有一个除以 2。
-
@BradBudlong,是的,刚刚看到了,但请注意,当 python 版本乘以 2 时,它也会除以 2
-
我可以复制你的 C++ 结果,但不能复制你的 python 结果。
标签: python c++ algorithm python-3.x triangle-count