Greatest Common Divisor from a set of more than 2 integers

后端 未结 13 1019
遇见更好的自我
遇见更好的自我 2020-12-09 04:25

There are several questions on Stack Overflow discussing how to find the Greatest Common Divisor of two values. One good answer shows a neat recursive function

13条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 05:23

    gcd(a1,a2,...,an)=gcd(a1,gcd(a2,gcd(a3...(gcd(a(n-1),an))))), so I would do it just step by step aborting if some gcd evaluates to 1.

    If your array is sorted, it might be faster to evaluate gcd for small numbers earlier, since then it might be more likely that one gcd evaluates to 1 and you can stop.

提交回复
热议问题