Javascript Number IsPrime()

Description

Javascript Number IsPrime()


// find the 10001st prime

Number.prototype.IsPrime = function() {
  var n = 2,/*from  w ww.  j  ava2  s  . co m*/
      isPrime = true;
  while (n < this / 2 && isPrime) {
    isPrime = this % n != 0;
    n++;
  }
  return isPrime;
}

var primeCount = 0,
    current = 1;

while (primeCount <= 10001) {
  current++;
  if (current.IsPrime()) {
    primeCount++;
  }
}

console.log(current);

Javascript Number isPrime()

Number.prototype.isPrime = function() {
  var primeCandidate = this;
  if(primeCandidate <= 1 || primeCandidate%1 !== 0) return false
  var i = 2;/*from ww  w . j ava  2s.com*/
  var top = Math.floor(Math.sqrt(primeCandidate));
  while(i<=top){
    if(primeCandidate%i === 0){ return false; }
    i++;
  }
  return true;
}

Javascript Number isPrime()

var util = require('util'),
    events = require('events');

// Quick and dirty prime checking.
Number.prototype.isPrime = function () {
  var i = 2;//from w w w .  j av  a2  s  . co  m
  while (i<=this - 1) {
    if (this % i ==0) {
      return false;
      break;
    }
    i++;
  }
  if (i == this) {
    return true;
  }
};

var Line = function(x1, y1, x2, y2) {
  var self = this;
  self['x1'] = x1;
  self['y1'] = y1;
  self['x2'] = x2;
  self['y2'] = y2;
};

Line.prototype = new events.EventEmitter();

Line.prototype.length = function() {
  var self = this;
  var length = Math.sqrt(
    Math.pow(Math.abs(self['x1'] - self['x2']), 2) +
    Math.pow(Math.abs(self['y1'] - self['y2']), 2)
  );
  if (length.isPrime()) {
    self.emit('prime');
  }
  self['line_length'] = length;
};

module.exports.create = function(x1, y1, x2, y2) {
  return new Line(x1, y1, x2, y2);
};



PreviousNext

Related