Sum multiples of 3 and 5: Difference between revisions

Content added Content deleted
Line 1,678: Line 1,678:


=={{header|J}}==
=={{header|J}}==

<lang J>
<lang J>
mp =: $:~ :(+/ .*) NB. matrix product
mp =: $:~ :(+/ .*) NB. matrix product
Line 1,721: Line 1,720:
(0,.10 10000 10000000000000000000x)+`-/"1@:(sum_arithmetic_series"1@:(,"1 0"1 _))3 5 15x
(0,.10 10000 10000000000000000000x)+`-/"1@:(sum_arithmetic_series"1@:(,"1 0"1 _))3 5 15x
23 23331668 23333333333333333331666666666666666668
23 23331668 23333333333333333331666666666666666668
</lang>
=== Simple Solution ===
The problem can also be solved with a simple use of inclusion/exclusion; this solution is more in keeping with how one could approach the problem from a more traditional language.
<lang J>
NB. Naive method
NB. joins two lists of the multiples of 3 and 5, then uses the ~. operator to remove duplicates.

echo 'The sum of the multiples of 3 or 5 < 1000 is ', ": +/ ~. (3*i.334), (5*i.200)


NB. inclusion/exclusion

triangular =: monad : '(y*(y + 1)) % 2'
sumdiv =: dyad : '(triangular <. x % y) * y'

echo 'For 10^20 - 1, the sum is ', ": +/ 99999999999999999999x sumdiv 3 5 _15
exit ''

</lang>
</lang>