FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaScript/Maths/DecimalExpansion.js at master · TheAlgorithms/JavaScript · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
TheAlgorithms
/
JavaScript
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
5.8k
Star
34.2k
Code
Issues
21
Pull requests
192
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaScript
/
Maths
/
DecimalExpansion.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
67 lines (57 loc) · 1.7 KB
Breadcrumbs
JavaScript
/
Maths
/
DecimalExpansion.js
Copy path
File metadata and controls
67 lines (57 loc) · 1.7 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
*
@author
Eric Lavault <https://github.com/lvlte>
*
* Represents the decimal (or binary, octal, any base from 2 to 10) expansion
* of a/b using euclidean division.
*
* Because this function is recursive, it may throw an error when reaching the
* maximum call stack size.
*
* Returns an array containing : [
* 0: integer part of the division
* 1: array of decimals (if any, or an empty array)
* 2: indexOf 1st cycle digit in decimals array if a/b is periodic, or undef.
* ]
*
*
@see
https://mathworld.wolfram.com/DecimalExpansion.html
*
*
@param
{
number
} a
*
@param
{
number
} b
*
@param
{
number
} [base=10]
*
@returns
{
array
}
*/
export
function
decExp
(
a
,
b
,
base
=
10
,
exp
=
[
]
,
d
=
{
}
,
dlen
=
0
)
{
if
(
base
<
2
||
base
>
10
)
{
throw
new
RangeError
(
'Unsupported base. Must be in range [2, 10]'
)
}
if
(
a
===
0
)
{
return
[
0
,
[
]
,
undefined
]
}
if
(
a
===
b
&&
dlen
===
0
)
{
return
[
1
,
[
]
,
undefined
]
}
// d contains the dividends used so far and the corresponding index of its
// euclidean division by b in the expansion array.
d
[
a
]
=
dlen
++
if
(
a
<
b
)
{
exp
.
push
(
0
)
return
decExp
(
a
*
base
,
b
,
base
,
exp
,
d
,
dlen
)
}
// Euclid's division lemma : a = bq + r
const
r
=
a
%
b
const
q
=
(
a
-
r
)
/
b
// Decimal expansion (1st element is the integer part)
exp
.
push
(
+
q
.
toString
(
base
)
)
if
(
r
===
0
)
{
// got a regular number (division terminates)
return
[
exp
[
0
]
,
exp
.
slice
(
1
)
,
undefined
]
}
// For the next iteration
a
=
r
*
base
// Check if `a` has already been used as a dividend, in which case it means
// the expansion is periodic.
if
(
a
in
d
)
{
return
[
exp
[
0
]
,
exp
.
slice
(
1
)
,
d
[
a
]
-
1
]
}
return
decExp
(
a
,
b
,
base
,
exp
,
d
,
dlen
)
}
Back
|
FazBrowse Home
|
New Git URL