Algorithms

by John Allan

JavaScript

Number.prototype.isPrime = function () {
	if (this === 1) return true;
  
  for (let i= 2; i < this; i++) {
  	if (this % i === 0) {
    	return false
    }
  }
  
  return true;

}

let x = 4;

console.log(x.isPrime());


Number.prototype.primeFactors = function () {
	let primes, primeFactors;
  
  primes = [];
  primeFactors = [];
  
  for (let i = 2; i < this; i++) {
  	if (this % i === 0) {
    	primes.push(i);
    }
  }
  
  for(let j = 0, l = primes.length; j < l; j++) {
  	if (this % primes[j] === 0) {
    	primeFactors.push(primes[j]);
    }
  }
  
  return primeFactors;
}

let y = 15;

console.log(y.primeFactors());

const nthFibonacci = (n) => {
	let f = [1, 1];
  
  if (n <= 1) return f[n];
  
  for (i = 0; i < n - 2; i++) {
  	f.push(f[i] + f[i+1])
  }
	
  return f[f.length - 1];

};

console.log(nthFibonacci(6));