I have written a code to check if the number is prime number are not.
I pass the number from command line argument, and check if the number is prime.
I have written a function for it which returns the boolean value.
(function(){
'use strict';
main();
function main(){
var testNum = getCommandLineVariables();
console.log("Is Number \""+testNum+"\" a prime number ? ",isPrimeNumber(testNum));
}
function isPrimeNumber(num){
var halfNum = num/2;
halfNum = parseInt(halfNum);
// check if number is divisible by 2,
// if yes then its not a prime number.
if(num%2 === 0){
return false;
}
do{
// if number is divisible by its half value,
// if yes, than its not prime number
if(num%halfNum === 0){
return false;
}
}while(--halfNum >= 2); // reduce the half-value by 1 and continue
return true;
} // end of isPrimeNumber
// get the number from commandline argument
function getCommandLineVariables(){
var arg_array = process.argv.slice(2);
if(arg_array.length !== 1){
throw new Error("Pass a number");
}
return parseInt(arg_array[0]);
} // end of getCommandLineVariables
})();
I run the program as follows,
E:\math>node isPrimeNum01.js 13
Is Number "13" a prime number ? true
E:\math>node isPrimeNum01.js 16
Is Number "16" a prime number ? false
E:\math>node isPrimeNum01.js 29
Is Number "29" a prime number ? true
E:\math>node isPrimeNum01.js 113
Is Number "113" a prime number ? true
E:\math>node isPrimeNum01.js 127
Is Number "127" a prime number ? true
E:\math>node isPrimeNum01.js 566
Is Number "566" a prime number ? false
E:\math>
Please review my code and leave your valuable comments. Also please check whether my logic for checking the prime number is efficient.