Skip to content

Instantly share code, notes, and snippets.

@nimamehanian
Last active December 15, 2015 09:29
Show Gist options
  • Save nimamehanian/5238760 to your computer and use it in GitHub Desktop.
Save nimamehanian/5238760 to your computer and use it in GitHub Desktop.
Find a collection of prime numbers between a range. I began with the primeNumbers function and wrote it the way I'd want to use it; go through a range and call prime() on each number. So that meant I had to create a prime() method for all Numbers using their prototype property. This lead me to research what rules define a number to be prime. The…
var primeNumbers = function(from, to) {
var primes = [];
for(var i = from; i <= to; i++){
if(i.prime()){
primes.push(i);
}
}
return primes;
};
Number.prototype.prime = function(){
if(this.even() && this !== 2 ||
this.sumOfDigitsDivByThree() && this !== 3 ||
this.lastTwoDigitsDivByFour() ||
this.lastDigitDivByFive() && this !== 5){
return false;
} else {
return true;
}
};
Number.prototype.even = function(){
if(this % 2 === 0){return true;}
};
Number.prototype.sumOfDigitsDivByThree = function(){
var sum = 0;
var digits = String(this).split('');
for(var i = 0, len = digits.length; i < len; i++){
sum += Number(digits[i]);
}
sum % 3 === 0 ? true : false;
};
Number.prototype.lastTwoDigitsDivByFour = function(){
var number = '';
var digits = String(this).split('');
var len = digits.length;
if(digits.length >= 2){
number += digits[len - 2];
number += digits[len - 1];
Number(number) % 4 === 0 ? true : false;
} else {
return false
}
};
Number.prototype.lastDigitDivByFive = function(){
var digits = String(this).split('');
var len = digits.length;
Number(digits[len - 1]) === 0 || Number(digits[len - 1]) === 5 ? true : false;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment