计数步骤python中的欧几里德算法程序(counting

编程入门 行业动态 更新时间:2024-10-24 10:15:53
计数步骤python中的欧几里德算法程序(counting-steps Euclidean algorithm program in python)

我需要一个程序来计算Euclid算法在Python中查找gcd(a,b)所需的步数。 该计划可能基于Lam'e定理。 到目前为止,我刚刚得到了简单的欧几里得算法程序:

def gcd(a, b): while b: a, b = b, a%b return a

我不知道如何编写我需要的程序。

I need a program to count the number of steps required by Euclid’s algorithm to find gcd(a, b) in Python. The program may based on Lam´e’s theorem. I just got the simple Euclidean algorithm program so far which is:

def gcd(a, b): while b: a, b = b, a%b return a

I have no idea how to write the program I need.

最满意答案

初始化一个计数器整数对象, count为零并在每次循环循环时递增它:

def gcd(a, b): count = 0 while b: a, b = b, a%b count += 1 print(count) return a

拉姆定理说,步count , count永远不会超过b中数字的5倍(数字越小)。 要验证这一点:

import math def gcd(a, b): ndigits = int(math.log10(b)) + 1 count = 0 while b: a, b = b, a%b count += 1 print(count) print("Lame's theorem holds?", count <= 5*ndigits) return a

Initialize a counter integer object, count to zero and increment it each time round the loop:

def gcd(a, b): count = 0 while b: a, b = b, a%b count += 1 print(count) return a

Lamé's theorem says that the number of steps, count will never exceed 5 times the number of digits in b (the smaller number). To verify this:

import math def gcd(a, b): ndigits = int(math.log10(b)) + 1 count = 0 while b: a, b = b, a%b count += 1 print(count) print("Lame's theorem holds?", count <= 5*ndigits) return a

更多推荐

本文发布于:2023-08-04 04:01:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1409359.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:欧几里德   算法   步骤   程序   counting

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!