簡體   English   中英

找到最大的公約數

[英]Find the greatest common divisor

def gei(a, b):
     '''
     a, b: only positive integers! If you don't, we will make you. Max 1337
     For extracting the juice of the numbers in the form of a common divider
     '''
     #Not Ruby, no to_i, but int()
     smallest = int(abs(min(a, b)))
     biggest = int(abs(max(a, b)))
     print "You inputed: ", smallest, " and ", biggest, " their order doesn't matter."
     print "Do you want to see guess numbers? Type 'yes', if you do! "
     selection = raw_input()
     print
     print
     #To evade infinite loops and too big numbers, we use count.
     count = 0
     ans = smallest
     truth = str(selection) == str('yes')
     def condition(ans, base):
         ans1 = base % ans == 0
         return ans1
     while condition(ans, biggest) == False or condition(ans, smallest) == False:
         ans -= 1
         count += 1
     if count >= 1337:
         break
     elif truth == True:
         print  ans
     if truth == True:
         print
         print
     print  "After weeks of calculation, here is your greater common divider: "
     return ans

是的,八年級的信息學作業要提取常見的更大的分隔線。 我想知道,也許你們知道我該如何減輕它的麻煩? 如何避免在內部使用定義並命名太多變量?

import fractions
print fractions.gcd(4,8)
>>> 4

但是您也可以查看來源:

def gcd(a, b):
    """Calculate the Greatest Common Divisor of a and b.

    Unless b==0, the result will have the same sign as b (so that when
    b is divided by it, the result comes out positive).
    """
    while b:
        a, b = b, a%b
    return a

參考: http//en.wikipedia.org/wiki/Euclidean_algorithm

使用Euclid算法

int GCD(int a,int b){
 if(b==0){
          return a;
 }
 return GCD(b,a%b);        
}

您的代碼中有一些可以改進的地方。

首先, truth是一個真正可憐的變量名,因為它並不能真正告訴您其內容的含義。 我會改用show_work東西。

接下來,您有一個內部函數,該函數告訴您一個變量將另一個變量平均除(返回布爾值)。 我建議直接使用模數值,而不是將其覆蓋為== 0的布爾== 0 ,並且您也不需要將其包含在函數中。 同樣,也不必將值與TrueFalse進行比較。 只需使用值本身(或not將其取反)。 將它們放在一起將使while循環的條件not biggest % ans and not smallest % ans s not biggest % ans and not smallest % ans s。

最后,您可以使用一種比逐個嘗試每個值更好的算法。 Euclid的算法是快速計算最大公除數的好方法,並且在Python中非常容易實現(但我留給您使用)。

這很不錯,並且沒有命名變量:

def gcd(a,b):
    return max(d for d in xrange(1, min(a, b)+1) if a % d == b % d == 0)

print gcd(15, 25)

>>> 5

但是請不要聲稱它是你自己的:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM