@gkucmierz/utils 1.16.1 → 1.16.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package-lock.json +2 -2
- package/package.json +1 -1
- package/spec/square-root.spec.mjs +22 -0
- package/src/square-root.mjs +10 -2
package/package-lock.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gkucmierz/utils",
|
|
3
|
-
"version": "1.16.
|
|
3
|
+
"version": "1.16.3",
|
|
4
4
|
"lockfileVersion": 2,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@gkucmierz/utils",
|
|
9
|
-
"version": "1.16.
|
|
9
|
+
"version": "1.16.3",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"devDependencies": {
|
|
12
12
|
"husky": "^8.0.1",
|
package/package.json
CHANGED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
|
|
2
|
+
import {
|
|
3
|
+
squareRoot,
|
|
4
|
+
squareRootBI,
|
|
5
|
+
} from '../src/square-root.mjs';
|
|
6
|
+
|
|
7
|
+
describe('square-root', () => {
|
|
8
|
+
it('squareRootBI small', () => {
|
|
9
|
+
expect(squareRootBI(0n)).toEqual(0n);
|
|
10
|
+
expect(squareRootBI(1n)).toEqual(1n);
|
|
11
|
+
expect(squareRootBI(2n)).toEqual(1n);
|
|
12
|
+
expect(squareRootBI(3n)).toEqual(1n);
|
|
13
|
+
expect(squareRootBI(4n)).toEqual(2n);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('squareRootBI 0-1e3', () => {
|
|
17
|
+
for (let i = 0; i < 1e3; ++i) {
|
|
18
|
+
const sqf = BigInt(Math.floor(i ** 0.5));
|
|
19
|
+
expect(squareRootBI(BigInt(i))).toEqual(sqf);
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
});
|
package/src/square-root.mjs
CHANGED
|
@@ -4,12 +4,20 @@ export const squareRoot = n => n ** 0.5;
|
|
|
4
4
|
|
|
5
5
|
// Newrton's formula
|
|
6
6
|
export const squareRootBI = n => {
|
|
7
|
+
if (n === 0n) return 0n;
|
|
8
|
+
if (n < 4n) return 1n;
|
|
9
|
+
if (n < 9n) return 2n;
|
|
10
|
+
if (n < 16n) return 3n;
|
|
7
11
|
let res = BigInt(n.toString().substr(0, n.toString().length / 2));
|
|
8
12
|
let last;
|
|
9
|
-
while (
|
|
13
|
+
while (true) {
|
|
10
14
|
last = res;
|
|
11
15
|
res = (res + n / res) / 2n;
|
|
12
|
-
|
|
16
|
+
const p = res * res;
|
|
17
|
+
if (p === n) return res;
|
|
18
|
+
if (last === res) return res;
|
|
19
|
+
const next = p + res * 2n - 1n;
|
|
20
|
+
if (n > next) return res;
|
|
13
21
|
}
|
|
14
22
|
return res;
|
|
15
23
|
};
|