primenumb
Version:
List or sum given number of prime numbers.
59 lines (49 loc) • 1.04 kB
JavaScript
exports.primenumb = function(nthp, liststuff)
{
if (!nthp)
{
console.log('You need to specify how many prime numbers you need. This is the first parameter. Zero is not an option.');
return false;
}
if (!liststuff)
{
console.log('You haven\'t specified if you need a list or not, so I\'ll give you a list.');
liststuff = true;
}
function isPrime(num)
{
if (num < 2)
return false;
for (var i = 2; i < num; i++)
if (num % i == 0)
return false;
return true;
}
function countPN(nthprime)
{
if (!nthprime) return false;
var result = 0, cntr = 0, primecntr = 0;
while (true)
{
if (isPrime(cntr))
{
if (liststuff)
console.log('Prime number: '+cntr);
else
result += cntr;
primecntr++;
}
if (primecntr >= nthprime)
break;
cntr++;
}
if (!liststuff)
{
console.log('The result is: ' + result);
return result;
}
console.log(cntr + ' number'+(cntr > 1 ? 's' : '')+' checked, ' + primecntr +' prime found.');
return true;
}
countPN(nthp);
}