mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
math: gcd and lcm functions
This commit is contained in:
committed by
Alexander Medvednikov
parent
0afcadcfd1
commit
7eab373922
@@ -68,6 +68,36 @@ pub fn fmod(a, b f64) f64 {
|
|||||||
return C.fmod(a, b)
|
return C.fmod(a, b)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// gcd calculates greatest common (positive) divisor (or zero if x and y are both zero).
|
||||||
|
pub fn gcd(a, b int) int {
|
||||||
|
if a < 0 {
|
||||||
|
a = -a
|
||||||
|
}
|
||||||
|
if b < 0 {
|
||||||
|
b = -b
|
||||||
|
}
|
||||||
|
for b != 0 {
|
||||||
|
a %= b
|
||||||
|
if a == 0 {
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
b %= a
|
||||||
|
}
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
|
// lcm calculates least common (non-negative) multiple.
|
||||||
|
pub fn lcm(a, b int) int {
|
||||||
|
if a == 0 {
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
res := a * (b / gcd(b, a))
|
||||||
|
if res < 0 {
|
||||||
|
return -res
|
||||||
|
}
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
pub fn log(a f64) f64 {
|
pub fn log(a f64) f64 {
|
||||||
return C.log(a)
|
return C.log(a)
|
||||||
}
|
}
|
||||||
|
|||||||
9
vlib/math/math_test.v
Normal file
9
vlib/math/math_test.v
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
import math
|
||||||
|
|
||||||
|
fn test_gcd_and_lcm() {
|
||||||
|
assert math.gcd(6, 9) == 3
|
||||||
|
assert math.gcd(6, -9) == 3
|
||||||
|
|
||||||
|
assert math.lcm(2, 3) == 6
|
||||||
|
assert math.lcm(-2, 3) == 6
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user