Skip to content
Kavachकवच

Math: Math functions

● Beginner2 min

sqrt, pow, gcd, lcm, is_prime, factorial, mean, and the constants pi and e.

use std.math

fn main() {
    print(math.sqrt(16.0))
    print(math.pow(2.0, 0.5))
    print(math.gcd(12, 18))
    print(math.is_prime(97))
    print(math.pi)
}

The program ran and printed:

kavach run functions.kav

4.01.41421356237309516true3.141592653589793
functions.kav: Kavach code, then what running it prints
NameGives
math.pi, math.eThe constants, as Float
math.sqrt(x), math.pow(x, y)For Float or Float32, giving the same type; a Float32 is worked out as a Float and rounded once
math.floor(x), math.ceil(x), math.round(x)The same; round rounds halves away from zero
math.gcd(a, b), math.lcm(a, b)Greatest common divisor and least common multiple of Ints
math.is_prime(n)Whether n is a prime number
math.factorial(n)n! for 0 <= n <= 20 (larger values don't fit in Int)
math.mean(xs)The average of a [Float], or none for an empty list