C++ 和 Python 中的算法相同,但输出不同
Same algorithm in c++ and python but different output
C++
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
unsigned long long int t,n,i,m,su,s,k;
int main()
{
cin>>n;
if(n==0)
{
cout<<"0n";
return 0;
}
m = sqrt(n);
su = m*(m+1)/2;
s = n-1;
for(i=2;i*i<=n;i++)
{
k = n/i;
s = s + (k-1)*i + k*(k+1)/2 - su;
}
cout<<s<<"n";
}
蟒
import math
n = int(input())
if n==0:
print('0')
else:
m = int(math.sqrt(n))
su = int(m*(m+1)/2)
s = n-1
i=2
while i*i<=n:
k = int(n/i)
s = s + ((k-1)*i) + int(k*(k+1)/2) - su
i = i+1
print(s)
10000000000的
答案不同对于 C++ 代码输出 = 322467033612360628
对于 Python 代码输出 = 322467033612360629
为什么答案不同?我不认为这是由 c++ 整数中的溢出引起的,因为在 64 位环境中,无符号长整整 int 的范围是 18,446,744,073,709,551,615
编辑:删除了造成混乱的变量 t
这与 Python
3 与 Python 2 中除法运算符的变化有关。
在 Python 2 中,如果分子和分母都是整数,则/
是整数下限除法:
Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/3
0
>>> 2.0/3.0
0.6666666666666666
>>>
>>> 1/2 == 1.0 / 2.0
False
请注意,在 Python 2 中,如果分子或分母是浮点数,则结果将是浮点数。
但是 Python 3 将/
更改为"真除法",您需要使用 //
来获取整数下限除法:
Python 3.3.2 (default, May 21 2013, 11:50:47)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/3
0.6666666666666666
>>> 2//3
0
>>> 1/2 == 1.0/2.0
True
>>> 1//2 == 1.0/2.0
False
C++使用整数之间的楼层划分:
int main()
{
int n=2;
int d=3;
cout<<n/d; // 0
}
如果我运行此代码(改编自您的):
from __future__ import print_function
import math
n = 1000000000
if n==0:
print('0')
else:
m = int(math.sqrt(n))
su = int(m*(m+1)/2)
s = n-1
i=2
while i*i<=n:
k = int(n/i)
s = s + ((k-1)*i) + int(k*(k+1)/2) - su
i = i+1
print(s)
在Python 3下,我得到:
322467033612360629
在Python 2下,我得到:
322467033612360628
如果更改此行:
s = s + ((k-1)*i) + int(k*(k+1)/2) - su
自
s = s + ((k-1)*i) + int(k*(k+1)//2) - su # Note the '//'
它将解决Python 3下的问题
相关文章:
- 双重释放或损坏(输出):使用向量的组合算法0x0000000001a880a0***
- 函数以相反的顺序输出输入问题,并改进算法以解释相等的数字
- 使用位移算法计算平方根始终输出相同的数字
- 使用数组找到最高分的算法并输出该索引(最高得分)
- 压缩算法(例如gzip、zip或snappy)的输出肯定小于输入吗
- 阵列调试不正确的输出,复杂算法
- C++ 表螺旋算法输出
- stl风格的算法:如何管理输出迭代器
- 二进制搜索树最佳拟合算法:输出不正确
- 算法输出正确答案,但编程挑战给了我错误的答案
- 将中值剪切颜色缩减算法的输出调色板应用于源图像
- C++ 和 Python 中的算法相同,但输出不同
- OpenCL计算与顺序算法的输出不匹配
- Dijkstra算法输出不正确
- 修改排列算法以防止重复打印输出的策略
- 输出“std::multiset”的唯一元素及其频率,使用C++中的std::算法(无循环)
- 是硬币变化算法,输出仍可由DP解决的所有组合
- 连接组件算法输出
- 为算法指定输入和输出范围
- OpenCV绘制一个椭圆从camshift算法输出