错了什么

2024-04-25 23:07:56 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我是python新手,用一个伪代码为karatsuba乘法编写了这个代码,得到了某种逻辑错误

下面是我使用的伪代码:

    procedure karatsuba(num1, num2)
  if (num1 < 10) or (num2 < 10)
    return num1*num2
  /* calculates the size of the numbers */
  m = max(size_base10(num1), size_base10(num2))
  m2 = m/2
  /* split the digit sequences about the middle */
  high1, low1 = split_at(num1, m2)
  high2, low2 = split_at(num2, m2)
  /* 3 calls made to numbers approximately half the size */
  z0 = karatsuba(low1,low2)
  z1 = karatsuba((low1+high1),(low2+high2))
  z2 = karatsuba(high1,high2)
  return (z2*10^(2*m2))+((z1-z2-z0)*10^(m2))+(z0)

下面是它的python代码:

def mul(n1,n2):

if n1<10 or n2<10:
    return n1*n2

l = max(len(str(n1)),len(str(n2)))
print(l)
half = l//2
print(half)

f1 = int(str(n1)[:half])
print("f1",f1)
l1 = int(str(n1)[half:])
print("l1",l1)
f2 = int(str(n2)[:half])
print("f2",f2)
l2 = int(str(n2)[half:])
print("l2",l2)

c = mul(l1,l2)
print("c",c)
b = mul((l1+f1),(l2+f2))
print("b",b)
a = mul(f1,f2)
print("a",a)

return ((a*10^(2*half))+((b-a-c)*10^(half))+c)
var = mul(44,21)
print(var)

如果有人做过这个算法,有人能告诉我哪里做错了吗?你知道吗

任何帮助都将不胜感激。你知道吗


Tags: thel1f2f1printstrn2mul
1条回答
网友
1楼 · 发布于 2024-04-25 23:07:56

你的问题可能来自你使用的指数运算。请注意

^xor运算符。你知道吗

**用于指数运算

>>> 2**3
8

或者等效地,您可以使用内置函数^{}

>>> pow(2, 3)
8

相关问题 更多 >