Mathematics
A mathematics library written in GoMelan is available.
To import it see the Includes page.
Source code for the mathematics library
fn power(x: Int, pow: Int) -> Int
{
if (pow <= 0) {
return 1;
}
return (power(x, pow - 1) * x);
}
fn abs(x: Int) -> Int
{
if (x < 0) {
return (x * -1);
}
return x;
}
fn factorial(x: Int) -> Int
{
if (x < 1) {
return x * factorial(x - 1);
}
return 1;
}
fn sum(a: [Int]) -> Int
{
s: Int = 0;
for (i: Int = 0; i < len(a); i++) {
s += a[i];
}
return s;
}
fn isPrime(n: Int) -> Bool
{
if (n <= 1) {
return false;
}
if (n == 2 || n == 3) {
return true;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
for (i: Int = 5; i * i <= n; i = i + 6) {
if ((n % i == 0) || (n % (i + 2) == 0)) {
return false;
}
}
return true;
}
Detailed infos
power
Calculate the power of an integer to another integer.
fn power(x: Int, pow: Int) -> Int;
Detailed Information:
Parameters:
x
: The base integer.pow
: The exponent integer.Return:
Returns
x
raised to the power ofpow
.Usage:
Example:
power(2, 3)
will return8
.
Error handling
If x
is 0
, the function returns 0
.
abs
Calculate the absolute value of an integer.
fn abs(x: Int) -> Int;
Detailed Information:
Parameter:
x
: The integer to calculate the absolute value for.Return:
Returns the absolute value of
x
.Usage:
Example:
abs(-5)
will return5
.
factorial
Calculate the factorial of an integer.
fn factorial(x: Int) -> Int;
Detailed Information:
Parameter:
x
: The integer to calculate the factorial for.Return:
Returns the factorial of
x
.Usage:
Example:
factorial(4)
will return24
.
Error handling
If x
is less than 1
, the function returns x
.
sum
Calculate the sum of an array of integers.
fn sum(a: [Int]) -> Int;
Detailed Information:
Parameter:
a
: An array of integers.Return:
Returns the sum of the integers in the array.
Usage:
Example:
sum([1, 2, 3])
will return6
.
isPrime
Determine if a given integer is a prime number.
fn isPrime(n: Int) -> Bool;
Detailed Information:
Parameter:
n
: The integer to check for primality.Return:
Returns
true
ifn
is a prime number, otherwise returnsfalse
.Usage:
Example:
isPrime(11)
will returntrue
.
Error handling
If n
is less than or equal to 1
, the function returns false
.
Last updated
Was this helpful?