【Python】俄罗斯农夫算法
相关介绍百度
直接上代码:
方法1:pandas法
import pandas as pd def half_double(n1, n2): halving = [n1] doubling = [n2] while min(halving) > 1: halving.append(math.floor(min(halving) / 2)) doubling.append(max(doubling) * 2) half_double = pd.DataFrame(zip(halving, doubling)) return half_double.loc[half_double[0] % 2 == 1, 1].sum() n1, n2 = 123456789, 987654321 half_double(n1, n2)
8ms出来结果
方法2:Python移位法(更快,更强)
%%time def RPM(a, b): p = 0 while a and b: if (b & 1): # b%2 p += a a <<= 1 else: a <<= 1 b >>= 1 return p print(RPM(123456789, 987654321)) print(123456789 * 987654321)
4ms出结果
-------------------------------
********厚德达理,励志勤工********
-------------------------------