* MyMath.js
function MyMath() {}
MyMath.abs = function(x) {
if (x < 0) {return -x;}
else return x;
}
MyMath.isPrime = function(/* int */n) {
if (n < 2) return false;
if (n === 2|| n===3) {
return true;
}
// 6x 6x+1 6x+2 6x+3 6x+4 6x+5
// 6x+2 => 2(3x+1)
// 6x+3 => 3(2x+1)
// 6x+4 => 2(3x+2)
if (n % 6 !== 1 && n % 6 !== 5) {
return false;
}
for (var x = 5; x * x <= n; x += 6) {
if (n % x === 0 || n % (x+2) === 0) {
return false;
}
}
return true;
}
MyMath.sqrt = function(/* Number */c) {
if (c < 0) return NaN;
var err = 1e-15;
var t = c;
while (MyMath.abs(t- c/t) > err * t) {
t = (c/t + t) / 2.0;
}
return t;
}
// hypotenuse of a right triangle
MyMath.hypotenuse = function(/* double */ a, /* double */b) /* double */ {
return MyMath.sqrt(a*a + b*b);
}
// Harmonic number
MyMath.H = function(/* int */ N) {
var sum = 0.0;
for (var i = 1; i <= N; i++) {
sum += 1.0 / i;
}
return sum;
}
module.exports = MyMath;
* index.js
const MyMath = require('./MyMath');
for (var i = 0; i < 100; i++) {
if (MyMath.isPrime(i)) {
console.log("Math.sqrt("+i+")=" + MyMath.sqrt(i));
}
}
console.log( MyMath.hypotenuse(3, 4) );
console.log( MyMath.H(1000) );
node index.js
Math.sqrt(2)=1.414213562373095
Math.sqrt(3)=1.7320508075688772
Math.sqrt(5)=2.23606797749979
Math.sqrt(7)=2.6457513110645907
Math.sqrt(11)=3.3166247903554
Math.sqrt(13)=3.6055512754639905
Math.sqrt(17)=4.123105625617661
Math.sqrt(19)=4.358898943540673
Math.sqrt(23)=4.795831523312719
Math.sqrt(29)=5.385164807134505
Math.sqrt(31)=5.567764362830022
Math.sqrt(37)=6.08276253029822
Math.sqrt(41)=6.4031242374328485
Math.sqrt(43)=6.557438524302
Math.sqrt(47)=6.855654600401045
Math.sqrt(53)=7.280109889280518
Math.sqrt(59)=7.681145747868609
Math.sqrt(61)=7.810249675906654
Math.sqrt(67)=8.18535277187245
Math.sqrt(71)=8.426149773176359
Math.sqrt(73)=8.544003745317532
Math.sqrt(79)=8.888194417315589
Math.sqrt(83)=9.1104335791443
Math.sqrt(89)=9.433981132056605
Math.sqrt(97)=9.848857801796104
5
7.485470860550343