Sum multiples of 3 and 5: Difference between revisions

J solution.
m (→‎version 2: final touches)
(J solution.)
Line 55:
print $ sumMulS 1000 [3,5]
print $ sumMulS 10000000 [2,3,5,7,11,13]</lang>
 
=={{header|J}}==
<lang J>
mp =: $:~ :(+/ .*) NB. matrix product
f =: (mp 0 = [: */ 3 5 |/ ])@:i.
assert 233168 -: f 1000
</lang>
For the efficient computation with large n, we start with observation that the sum of these multiples with the reversed list follows a pattern.
<lang J>
g =: #~ (0 = [: */ 3 5&(|/))
assert 0 3 5 6 9 10 12 15 18 20 21 24 25 27 30 33 35 36 39 40 42 45 48 -: g i. 50
assert 48 48 47 46 48 46 47 48 48 47 46 48 46 47 48 48 47 46 48 46 47 48 48 -: (+ |.)g i. 50 NB. the pattern
 
assert (f -: -:@:(+/)@:(+|.)@:g@:i.) 50 NB. half sum of the pattern.
 
NB. continue...
</lang>
 
=={{header|NetRexx}}==
Anonymous user