mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
math: sqrti, powi, factoriali (#12072)
This commit is contained in:
@@ -35,6 +35,41 @@ pub fn pow10(n int) f64 {
|
||||
return 0.0
|
||||
}
|
||||
|
||||
// powi returns base raised to power (a**b) as an integer (i64)
|
||||
//
|
||||
// special case:
|
||||
// powi(a, b) = -1 for a = 0 and b < 0
|
||||
pub fn powi(a i64, b i64) i64 {
|
||||
mut b_ := b
|
||||
mut p := a
|
||||
mut v := i64(1)
|
||||
|
||||
if b_ < 0 { // exponent < 0
|
||||
if a == 0 {
|
||||
return -1 // division by 0
|
||||
}
|
||||
return if a * a != 1 {
|
||||
0
|
||||
} else {
|
||||
if (b_ & 1) > 0 {
|
||||
a
|
||||
} else {
|
||||
1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for ; b_ > 0; {
|
||||
if b_ & 1 > 0 {
|
||||
v *= p
|
||||
}
|
||||
p *= p
|
||||
b_ >>= 1
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
// pow returns base raised to the provided power.
|
||||
//
|
||||
// todo(playXE): make this function work on JS backend, probably problem of JS codegen that it does not work.
|
||||
|
||||
Reference in New Issue
Block a user