Kata comeback

Some of the katas I completed were withdrawn.  However the solutions still exist.

One of these was for determining a prime number including negative numbers.

The rules for a prime number are that it is an integer or natural number and is positively divisible only by 1 or itself.

 

With this I was fairly confident and wrote out my solution

function PrimeTest(a)

{

                if (a <2)

{

                        return false;

}

                for(var i = 2; i < a; i++)

{

                       if(a % i === 0)

{

                                 return false;

}

}

                return true;

}

This was a good solution although I’m aware that I do not need to add the curly brackets for the if and for loops as they only are one statement, I like it to look neat and I find it easier to read this way.  One of the best practice ways was exactly done this way, this pleased me and I could handle that.  Of course as we know in programming there is more than one way to skin a cat.

function PrimeTest(a){

                for (var i = 2; i < a / 2; i++)

                            if (!(a % i))

                                   return false;

                return a >= 2;

};

However cool this code was there is a problem when a = 4 it will return true.  Someone else came up with the idea of amending it slightly.

function PrimeTest(a){

               for(var i = 2; i <= a / 2; i++){

                              if (!(a % i))

                                       return false;

}

                return a > 1;

};

More clever than mine.  However I feel my answer was not too bad.

Leave a Reply

Your email address will not be published. Required fields are marked *