0
votes

I'm trying to sum all numbers from 1 to 1000 that are either divisible by 3 or 5.

The first attempt is straight forward:

ans1 = 0
for x in 3:999
    ans1 += x % 3 == 0 || x % 5 == 0 ? x : 0 
end

When I try the same approach using function chaining, it fails to return the answer I expect, it instead returns 0.

ans2 = [3:999] |> x -> x % 3 == 0 || x % 5 == 0 ? x : 0 |> sum

I believe the problem is the center function, since the code below prints all values within the range of 3 to 999. So i know there is no problem with iteration.

[3:999] |> x -> println(x)

Could anyone please help me.

1
I almost voted to close due to this being an exact duplicate, however, on second thought, although the problem is identical, the question itself is quite different. Also, I can't quite help myself and feel compelled to add that a better way to solve the initial problem is via the one-liner sum([3:3:1000] + sum([5:5:1000]) - sum([15:15:1000]) :-)Colin T Bowers
I wouldn't blame you if did, it's a popular problem from the famous Project Euler site. Although my question was, how could I solve that problem with function chaining. That said, I found it was a bad way to solve the problem. ans3 in my answer turned out to be the best of all the approaches I've taken. But yes, you're exactly right! That is a great solution to the problem, thank you for your comment! :D I must say, Julia is a great language. I started with it yesterday solving Project Euler problems.Warosaurus
Sounds like a good way to learn the language. I found I really enjoyed it to start also. Then, when I worked on larger projects, I enjoyed it even more! The fully typed system combined with multiple dispatch just feel like the "right" way to write more complex bits of software.Colin T Bowers

1 Answers

0
votes

I discovered the reason was because I did not understand the type being parsed. Here is an example:

[3:999] |> println(typeof(x)) # Array{Int64,1}

Meaning the value being parsed is an array of integer64. So evaluating the following:

[1:999] % 3 == 0 # false

So my answer was to instead use the filter function, here is an example:

ans3 = sum(filter(x -> x % 3 == 0 || x % 5 == 0,[1:999]))

The final answer using function chaining is:

ans4 = [1:999] |> x -> filter(y -> y % 3 == 0 || y % 5 == 0,x) |> sum

Which evaluates to the expected answer.