Count in factors: Difference between revisions

Content added Content deleted
(added a solution for Factor)
Line 1,735: Line 1,735:


=={{header|Julia}}==
=={{header|Julia}}==
<lang Julia>
{{works with|Julia|0.6}}
function factor_print{T<:Integer}(n::T)
const SEP = " \u00d7 "
-2 < n || return "-1"*SEP*factor_print(-n)
if isprime(n) || n < 2
return string(n)
end
a = T[]
for (k, v) in factor(n)
append!(a, k*ones(T, v))
end
sort!(a)
join(a, SEP)
end


<lang julia>using Primes
lo = -4
function strfactor(n::Integer)
hi = 40
n > -2 || return "-1 × " * strfactor(-n)
println("Factor print ", lo, " to ", hi)
isprime(n) || n < 2 && return dec(n)
for i in lo:hi
f = factor(Vector{typeof(n)}, n)
println(@sprintf("%5d = ", i), factor_print(i))
return join(f, " × ")
end
end

</lang>
lo, hi = -4, 40
I wrote this solution's <tt>factor_print</tt> function with ease rather than efficiency in mind. It may be more efficient to first sort the keys of the <tt>factor</tt> dictionary and to build the string in place, but I find the logic of the presented solution to be clearer. The <tt>factor</tt> built-in is relevant to this solution only for integers greater than <tt>1</tt>, but I've constructed <tt>factor_print</tt> to return meaningful results for any representable proper integer.
println("Factor print $lo to $hi:")
for n in lo:hi
@printf("%5d = %s\n", n, strfactor(n))
end</lang>


{{out}}
{{out}}
<pre>Factor print -4 to 40:
<pre>
Factor print -4 to 40
-4 = -1 × 2 × 2
-4 = -1 × 2 × 2
-3 = -1 × 3
-3 = -1 × 3
Line 1,806: Line 1,797:
38 = 2 × 19
38 = 2 × 19
39 = 3 × 13
39 = 3 × 13
40 = 2 × 2 × 2 × 5
40 = 2 × 2 × 2 × 5</pre>
</pre>


=={{header|Kotlin}}==
=={{header|Kotlin}}==