Saturday, March 18, 2023

Coding Challenge #25

 // from https://www.codecademy.com/resources/blog/20-code-challenges/
// test if a given number is prime
// we will test this by checking if it is greater than 1 (if not, fail)
// we will then multiply numbers below it to try to achieve the given number (if we cannot achieve it, it is prime: success)
function isPrime(n){
    if(n < 2) return false; // too small to be prime
    // since only 2+ can multiply together to be prime, we only need to check [2, half of n]
    for(var xint = 2, len = Math.ceil(n / 2) + 1;xint < len;xint++){
        for(var yint = 2;yint < len;yint++){
            var x = xint * yint;
            if(x == n) return false; // achieved the given number as a product
            if(x > n) break; // no further numbers would pass either
        }
    }
    return true;
}

No comments:

Post a Comment

Coding Challenge #54 C++ int to std::string (no stringstream or to_string())

Gets a string from an integer (ejemplo gratis: 123 -> "123") Wanted to come up with my own function for this like 10 years ago ...