Function Examples

Daily life functions

Convert weight in grams to weight in ounces.
def gramsToOunces(g)=g*0.0353;
  
Convert weight in ounces to weight in grams.
def ouncesToGrams(o)=o*28.35;

Convert Celsius temperature to Fahrenheit temperature
 def CelsiusToFahrenheit(c)=c*9/5+32;
 
Convert Fahrenheit temperature to Celsius temperature
def FahrenheitToCelsius(f)=(f-32)*5/9;

Convert length in centimeters to length in inches
 def centimetersToInches(c)=c*0.3937;
 
Convert length in inches to length in centimeters
def inchesToCentimeters(i)=i*2.54;


Mathematic functions

Number 'n' is prime number?
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;
}

Find n-th prime number
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;
}



Comments

Post a Comment

Popular posts from this blog

Prompt for AI

How Deep Is the Well?