Arithmetic/Rational: Difference between revisions

→‎{{header|Julia}}: Updated for Julia 1.2
(→‎{{header|Julia}}: Updated for Julia 1.2)
Line 1,910:
=={{header|Julia}}==
Julia has native support for rational numbers. Rationals are expressed as <tt>m//n</tt>, where <tt>m</tt> and <tt>n</tt> are integers. In addition to supporting most of the usual mathematical functions in a natural way on rationals, the methods <tt>num</tt> and <tt>den</tt> provide the fully reduced numerator and denominator of a rational value.
<lang{{works with|Julia>|1.2}}
<lang Julia>using Primes
function isperfect{T<:Integer}(n::T)
divisors(n) = foldl((a, (p, e)) -> vcat((a * [p^i for i in 0:e]')...), factor(n), init=[1])
!isprime(n) || return false
tal = 1//n
hi = isqrt(n)
if hi^2 == n
tal += 1//hi
hi -= 1
end
for i in 2:hi
(d, r) = divrem(n, i)
if r == 0
tal += (1//i + 1//d)
end
end
return tal == 1//1
end
 
isperfect(n) = sum(1 // d for d in divisors(n)) == 2
lo = 2
 
lo, hi = 2, 2^19
println("Searching for perfect numbers from ", lo, " to ", hi, ".")
println("Perfect numbers between ", lo, " and ", hi, ": ", collect(filter(isperfect, lo:hi)))
for i in 2:2^19
isperfect(i) || continue
println(@sprintf("%8d", i))
end
</lang>
 
{{out}}
<pre>
Searching for perfectPerfect numbers frombetween 2 toand 524288.: [6, 28, 496, 8128]
6
28
496
8128
</pre>