Terminating, Purely Periodic, or Eventually Periodic?
JavaScript (ES6), 70 .. 68 53 bytes
f=(a,b,s=[],x)=>a?(s[a]^=a)?f(a*10%b,b,s,x||a):x==a:0
Returns 0 for terminating, true for purely periodic and false for eventually periodic.
How it works
What we're doing here is actually simulating a division by hand:
a?...:0
- If the numerator is zero, we stop here and return0
. The sequence is terminating.(s[a]^=a)?...:x==a
- If we've already encountered this numerator before, it means that the sequence is periodic and is going to repeat forever. We stop here and return eithertrue
ifa
is equal to the first valuex
of the sequence (purely periodic) orfalse
if it's not (eventually periodic).f(a*10%b,b,s,x||a)
- Else, we multiply the numeratora
by 10. We compute the remainder of the division by the denominatorb
. And we repeat the process by using this remainder as the new numerator. (We also passa
as the first value of the sequence if it's not already stored inx
.)
Example
- Blue: numerator = 1
- Green: denominator = 7
- Red: multiplications by 10
- Black: remainders
- Gray: quotient digits (we don't really care about them here, and the above code is not computing them at all)
Python, 62 61 59 bytes
f=lambda n,d,r=[0,0]:(r[:3]+r).count(n)or f(10*n%d,d,r+[n])
Prints 1 for eventually periodic, 2 for purely periodic, and 4 for terminating.
Verify all test cases on repl.it.
Jelly, 10 bytes
:gÆfḍ⁵ṢQ¬Ḅ
Accepts denominator and numerator (in that order) as arguments. Returns 0 for terminating, 1 for purely periodic, and 2 for eventually periodic. Try it online! or verify all test cases.
How it works
:gÆfḍ⁵ṢQ¬Ḅ Main link. Arguments: d (denominator), n (numerator)
g Compute the GCD of d and n.
: Divide d by the GCD, yielding the denominator of the simplified form.
Æf Yield all prime factors of the previous result.
ḍ⁵ Test 10 for divisibility by each prime factor.
This yields 1 for 2 and 5, 0 for all other primes.
Ṣ Sort the resulting Booleans.
Q Unique; deduplicate the sorted Booleans.
¬ Logical NOT; replace 0 with 1 and vice versa to yield one of the
following arrays.
[ ] <- no prime factors (denominator 1)
[ 0] <- only 2 and 5
[1 ] <- neither 2 nor 5
[1, 0] <- mixed
Ḅ Unbinary; convert from base 2 to integer.
This maps [] and [0] to 0, [1] to 1, and [1, 0] to 2.