How to resolve the algorithm Sum multiples of 3 and 5 step by step in the J programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sum multiples of 3 and 5 step by step in the J programming language
Table of Contents
Problem Statement
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sum multiples of 3 and 5 step by step in the J programming language
Source code in the j programming language
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. slightly less naive: select the numbers which have no remainder when divided by 3 or 5:
echo 'The sum of the multiples of 3 or 5 < 1000 is still ', ": +/I.+./0=3 5|/i.1000
NB. inclusion/exclusion
triangular =: -:@:(*: + 1&*)
sumdiv =: dyad define
(triangular <. x % y) * y
)
echo 'For 10^20 - 1, the sum is ', ": +/ (".(20#'9'),'x') sumdiv 3 5 _15
You may also check:How to resolve the algorithm Stern-Brocot sequence step by step in the EchoLisp programming language
You may also check:How to resolve the algorithm Multiplication tables step by step in the DCL programming language
You may also check:How to resolve the algorithm SHA-256 step by step in the Objective-C programming language
You may also check:How to resolve the algorithm Steffensen's method step by step in the Phix programming language
You may also check:How to resolve the algorithm Sum of elements below main diagonal of matrix step by step in the Java programming language