0

我正在尝试制作一个模型类来找到 2 个数字的格栅共同除法。如果我输入 68 和 22 答案是 2 并且是正确的,但如果我输入 678 352 结果是 326 并且是错误的!应该是2!有任何想法吗??

def gcd 
  if firstnumber > secondnumber
    div= firstnumber/ secondnumber
    ip=firstnumber % secondnumber
    fi = div / ip
    ip
  else 
    i = firstnumber 
    s = secondnumber 
    secondnumber = firstnumber 
    firstnumber = s 
    div= firstnumber/ secondnumber 
    ip=firstnumber % secondnumber 
    fi = div / ip ip 
  end 
end

带循环

def gcd
   a = firstnumber
   b=secondnumber
   ip = 50
   if firstnumber > secondnumber
     begin   
       fi=a/b
       re=a%b    
       fi=b/re
       re=re%b
       ip=re        
     end until ip != 0
     return re  
   end
   else
     i = firstnumber
     s = secondnumber
     secondnumber = firstnumber
     firstnumber = s
     div= firstnumber/ secondnumber
     ip=firstnumber % secondnumber
     fi = div / ip
     ip
   end
end

$结束

同样的事情也会发生

4

1 回答 1

1

Ruby 有一个Integer具有方法的类gcd。不要重新发明轮子。在这里阅读http://www.ruby-doc.org/core-1.9.3/Integer.html#method-i-gcd

irb(main):001:0> 68.gcd(22)
=> 2
irb(main):002:0> 678.gcd(352)
=> 2

该方法的来源是

   def gcd(n)
     m = self.abs
     n = n.abs

     return n if m == 0
     return m if n == 0

     b = 0
     while n[0] == 0 && m[0] == 0
       b += 1; n >>= 1; m >>= 1
     end
     m >>= 1 while m[0] == 0
     n >>= 1 while n[0] == 0
     while m != n
       m, n = n, m if n > m
       m -= n; m >>= 1 while m[0] == 0
     end
     m << b
   end
于 2012-05-24T17:00:06.157 回答