Skip to content

Instantly share code, notes, and snippets.

@fernandoporazzi
Last active August 29, 2015 14:03
Show Gist options
  • Save fernandoporazzi/54d860d07a17b1bb0905 to your computer and use it in GitHub Desktop.
Save fernandoporazzi/54d860d07a17b1bb0905 to your computer and use it in GitHub Desktop.
Detect if a given word is prime according to their letter positions in alphabet.
var alphabet = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
];
// get char position in array
function stringToNumber (string) {
var number = 0;
for ( var i = 0, l = string.length; i < l; i++ ) {
var indexOfChar = alphabet.indexOf(string[i]) + 1;
number = number + indexOfChar;
}
return number;
}
// detect if a given number is prime
function isPrime (word, number) {
console.log('Valor: ' + number);
var result;
if (number === 1) {
// 1 will never be prime
result = false;
} else if (number === 2) {
// 2 is the only even number to be prime
result = true;
} else { // if number is not 1 or 2....
// test if it is even
if ( number % 2 === 0 ) {
// number can't be divisible by any other number unless 1 or itself
// the only even number is 2
result = false;
} else {
// loop start at 2 and ends at "number - 1"
// We do this trick because every number can be divided by 1 and itself
for (var i = 2; i < number; i++) {
// number can't be divisible by any other number unless 1 or itself
if ( number % i === 0 ) {
result = false;
// exit loop
break;
} else {
// aha, we got a prime number
result = true;
}
}
}
}
if (result) {
console.log(word + ' IS a prime word');
} else {
console.log(word + ' IS NOT a prime word');
}
}
var wordToTest = 'Fernando';
// returns 103
var number = stringToNumber(wordToTest);
// arguments('Fernando', 103)
isPrime(wordToTest, number);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment