looks fine, with similar structure,

3 5 (i.@] #~ +./@:(0&=)@:(|"0 1 i.)) 19

or shorter

3 5 (i.@] #~ +./@:(0&=)@:(|/ i.)) 19



----- Original Message -----
From: Geoff Canyon <gcan...@gmail.com>
To: programm...@jsoftware.com
Sent: Wednesday, May 4, 2016 10:35 PM
Subject: [Jprogramming] Project Euler 1

So I tried to write code to solve the general case of Project Euler problem
1. The problem given is to find the sum of all the positive integers less
than 1000 that are divisible by 3 or 5. Obviously the specific case is
highly optimizable. But I wanted to solve the general, with any number of
divisors and any upper limit.

So I started by enumerating the integers from 0 to the limit, and finding
the remainder for each list when divided by each of the divisors.

Then I transpose and multiply, so the list is now 0 for each integer
divisible by any of the divisors.

Then I search for 0 in the list, so I end up with 1 for numbers that are
divisible by any of the divisors, and 2 for numbers that aren't.

Then I subtract that list from 1, so divisible numbers are 1, and
non-divisible numbers are 0.

Then I enumerate from 0 to the limit again, and multiply the two lists, so
I have a list with 0 for the numbers that are non-divisible, and the
numbers when they are divisible.

Then I sum that list, and that's the result.

Here's the code. As always, I suck at J, so improvements/suggestions are
welcome.

pe1 =: +/@(([:i.]) * 1&-@(0&i.)@*/"1@|:@(|"0 1 i.))


1 pe1 10 NB. sum of 1..9

45


2 pe1 101 NB. sum of the first 50 even numbers

5050


2 3 5 7 11 13 17 19 23 29 pe1 1000 NB. difficult to do the "optimized" way

305863
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm 
----------------------------------------------------------------------
For information about J forums see http://www.jsoftware.com/forums.htm

Reply via email to