I'm trying to find the number less than 1000 that produces the longest string of repeated numbers when it divides 1. I have a list of decimal numbers and have to find the ones which have the longest repeated sequence.
Here's what I have so far
numbers = [*2..999]
decimal_representations = numbers.map { |number| 1.to_f/number }
decimal_representations.map!(&:to_s)
I can produce a three dimensional array by using regex. Regex /(.+)\1+/
produces an array of repeated substrings. I want to find the longest substring, so I used enumerable's max_by
function.
decimal_representations.map! { |decimal| decimal.scan(/(.+)\1+/).max_by(&:length) }.flatten
I have to compact my array to remove nil
elements
decimal_representations.compact!
Then I can find out which had the longest length.
decimal_representations.max_by(&:length)
I get 0090009009
, but I can't figure out which number had that decimal value, because I removed nil elements from my array.
Any ideas?
Hi, I'm Charlie Kasov, and this is what is the longest repeating decimal, and the answer to that is there is no one longest repeating decimal. Any repeating decimal that is infinite is going to go on to infinity, so all of them would be equally long. For example, if we have two-thirds, that equals .
A decimal number with a digit (or group of digits) that repeats forever. The part that repeats can also be shown by placing dots over the first and last digits of the repeating pattern, or by a line over the pattern.
A repeating decimal, also called a recurring decimal, is a number whose decimal representation eventually becomes periodic (i.e., the same sequence of digits repeats indefinitely).
When two digits recur multiply by 100 so that the recurring digits after the decimal point keep the same place value. Similarly, when three digits recur multiply by 1000 and so on.
Float
can't represent most decimal numbers precisely, so using (1.to_f/number).to_s
probably won't give you the expected result. This means your whole algorithm is incorrect.
You need a different algorithm. Here's a hint: 1.0 / 7
in math produce a decimal 0.142857142857...
, the repeated sequence is 142857
. If you do this division using, you'll notice that 142857
is a divisor of 999999
, which is not a coincidence.
Numbers that are multiples of 2
or 5
need some extra attention. The trick is that, for example, 14
(7 * 2
) or 35
(7 * 5
), have the same number of repeated sequence in their 1.0 / n
decimal representation.
It's a little difficult to explain this idea without code. I have solved this Project Euler problem, but hope that you can solve it without looking at my source code first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With