2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Javascriptで最大公約数を求める式をモダンな記法で書きたい

Posted at

最大公約数の求め方

ユークリッド互除法 大きい方の整数Aを小さい方の整数Bで割った余りをR とするとき,A, Bの組の替わりにB, Rの組に順次置き換えて,R=0となったときのBを最大公約数とする

レガシーな書き方

function gcd (x, y){
  if(x % y){
    return gcd(y, x % y)
  }else{
    return y
  }
}
console.log(gcd(480,1024)) // 32

モダンなコード

const gcd = (x, y) => x % y ? gcd(y, x % y) : y
console.log(gcd(480,1024)) // 32

or

const gcd = (a, b) => !b ? a : gcd(b, a % b)
console.log(gcd(480,1024)) // 32

もっと面白い(変態的な)書き方あるよってあったら教えて下さい。

2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?