Sunday, August 12, 2012

Using recursion to find prime numbers

Occasionally I like to go back over basic programming concepts by doing simple programming exercises. It's a good practice that I think any developer can benefit from. Today I've been doing some JavaScript and found myself needing to do a google search to remind myself about recursive functions as they're not something I use often. There seem to be loads of horrible examples out there so I've decided to post the code I ended up using.
for (counter = 1; counter <= 23; counter++) {
    if (isPrime(counter, counter -1)) {
        console.log(counter + " is a prime numer.");

function isPrime(number, step) {
    if(step <=1)
        return true;
    if(number % step === 0) {
        return false;
    return isPrime(number, step-1);

No comments: