n-th prime number

Let's create a math function that calculates n-th prime number in the factory page in the Function Calculator.
In order to create that function we need to create a helper function that determines whether a number is prime number or not first as below.

def isPrime(n) {
    if (n <= 1) {
        return false;
    }
    var i = 2;
    while (i * i <= n) {
        if (n % i == 0) {
            return false;
        }
        i = i + 1;
    }
    return true;
}

Using above helper function we can create the function as below.

def nthPrime(n) {
    var count = 0;
    var num = 2;
    while (count < n) {
        if (isPrime(num)) {
            count = count + 1;
        }
        if (count == n) {
            return num;
        }
        num = num + 1;
    }
    return num - 1;
}

After create math functions click run button to execute code and click save button to save in the database.
Return to the Calculator page and click F2 button and select the math function you just created and calculate.


Comments

Popular posts from this blog

Prompt for AI

How Deep Is the Well?

Function Examples