Factors of an integer: Difference between revisions
J: use a more structurally illustrative examples and some other changes to hopefully make the concepts clearer
m (No, it's a real language of programmable calculators.) |
(J: use a more structurally illustrative examples and some other changes to hopefully make the concepts clearer) |
||
Line 997:
Alternatively, q: can produce provide a table of the exponents of the unique relevant prime factors
<lang J> __ q:
With this, we can form lists of each of the potential relevant powers of each of these prime factors
<lang J> ((^ i.@>:)&.>/) __ q:
┌─────┬───┬───┬───┐
└─────┴───┴───┴───┘</lang>
From here, it's a simple matter (<code>*/&>@{</code>) to compute all possible factors of the original number
<lang J>
factrs 40
<lang J>factors 40▼
1 5
2 10
Line 1,016 ⟶ 1,015:
8 40</lang>
However, a data structure which is organized around the prime decomposition of the argument can be hard to read. So, for reader convenience, we should probably arrange them in a monotonically increasing list:
A less efficient approach, in which remainders are examined up to the square root, larger factors obtained as fractions, and the combined list nubbed and sorted:▼
<lang J>factors=: monad define▼
<lang J> factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__
Y=. y"_▼
/:~ ~. ( , Y%]) ( #~ 0=]|Y) 1+i.>.%:y▼
1 2 3 4 5 6 7 10 12 14 15 20 21 28 30 35 42 60 70 84 105 140 210 420</lang>
A less efficient, but concise variation on this theme:
Line 1,029 ⟶ 1,028:
This computes 2^n intermediate values where n is the number of prime factors of the original number.
▲
▲ Y=. y"_
▲ /:~ ~. ( , Y%]) ( #~ 0=]|Y) 1+i.>.%:y
)
factorsOfNumber 40
1 2 4 5 8 10 20 40</lang>
|