4
4
* @see {@link https://projecteuler.net/problem=26 }
5
5
*
6
6
* Find the value of denominator < 1000 for which 1/denominator contains the longest recurring cycle in its decimal fraction part.
7
- *
8
- * A unit fraction (1/denominator) either terminates or repeats. We need to determine the length of the repeating sequence (cycle)
9
- * for each fraction where the denominator is between 2 and 999, and find the denominator that produces the longest cycle.
10
7
*/
11
8
12
9
/**
@@ -23,49 +20,37 @@ function findLongestRecurringCycle(limit) {
23
20
* @returns {number } The length of the recurring cycle in the decimal part of 1/denominator.
24
21
*/
25
22
function getRecurringCycleLength ( denominator ) {
26
- // A map to store the position of each remainder encountered during division
27
23
const remainderPositions = new Map ( )
28
- let numerator = 1 // We start with 1 as the numerator (as we're computing 1/denominator)
29
- let position = 0 // This tracks the position of each digit in the decimal sequence
24
+ let numerator = 1
25
+ let position = 0
30
26
31
- // Continue until the remainder becomes 0 (terminating decimal) or a cycle is found
32
27
while ( numerator !== 0 ) {
33
- // If the remainder has been seen before, we've found the start of the cycle
34
28
if ( remainderPositions . has ( numerator ) ) {
35
- // The length of the cycle is the current position minus the position when the remainder first appeared
36
29
return position - remainderPositions . get ( numerator )
37
30
}
38
31
39
- // Record the position of this remainder
40
32
remainderPositions . set ( numerator , position )
41
33
42
- // Multiply numerator by 10 to simulate long division and get the next digit
43
34
numerator = ( numerator * 10 ) % denominator
44
- position ++ // Move to the next digit position
35
+ position ++
45
36
}
46
37
47
- // If numerator becomes 0, it means the decimal terminates (no cycle)
48
38
return 0
49
39
}
50
40
51
- let maxCycleLength = 0 // Store the maximum cycle length found
52
- let denominatorWithMaxCycle = 0 // Store the denominator corresponding to the longest cycle
41
+ let maxCycleLength = 0
42
+ let denominatorWithMaxCycle = 0
53
43
54
- // Iterate through each possible denominator from 2 up to (limit - 1)
55
44
for ( let denominator = 2 ; denominator < limit ; denominator ++ ) {
56
- // Calculate the cycle length for the current denominator
57
45
const cycleLength = getRecurringCycleLength ( denominator )
58
46
59
- // Update the maximum length and the corresponding denominator if a longer cycle is found
60
47
if ( cycleLength > maxCycleLength ) {
61
48
maxCycleLength = cycleLength
62
49
denominatorWithMaxCycle = denominator
63
50
}
64
51
}
65
52
66
- // Return the denominator that has the longest recurring cycle
67
53
return denominatorWithMaxCycle
68
54
}
69
55
70
- // Exporting the main function for use in other modules
71
56
export { findLongestRecurringCycle }
0 commit comments