xwill

To be double-cool

28 Apr 2024

最大公约数,最大公倍数

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
	func gcd(a, b int) int {
		for b != 0 {
			tmp := b
			b = a%b
			a = tmp
		}
		return a
	}

	// a%b a除以b的余数
	// a<b 余数为a
1
2
3
	func lcm(a,b int) int {
		return a*b/gcd(a,b)
	}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
	func ngcd(nums []int) int {
		size := len(nums)
		if size == 0 {
			panic("empty nums")
		}
		if size == 1{
			return nums[0]
		}
		x := nums[0]
		for i:=1; i<size; i++ {
			x = gcd(x, nums[i])
		}
		return x
	}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
	func nlcm(nums []int) int {
		size := len(nums)
		if size == 0 {
			panic("empty nums")
		}
		if size == 1{
			return nums[0]
		}
		x := nums[0]
		for i:=1; i<size; i++ {
			x = (x * nums[i]) / gcd(x, nums[i])
		}
		return x
	}