If we list all the natural numbers below \(10\) that are multiples of \(3\) or \(5\) , we get \(3, 5, 6\) and \(9\) . The sum of these multiples is \(23\) . Find the sum of all the multiples of \(3\) or \(5\) below \(1000\) .
https://projecteuler.net/problem=1
R
Development
We can start with the the first statement, as it eases us into the problem solving.
Finding the sum of all the multiples of \(3\) or \(5\) in the set of natural numbers below \(10\) :
Code threes <- 0
fives <- 0
for ( i in 1 : 10 - 1 ) {
if ( i %% 5 == 0 ) fives <- c ( fives , i )
if ( i %% 3 == 0 ) threes <- c ( threes , i )
}
sum ( unique ( c ( threes , fives ) ) )
Answer 1
The sum of all the multiples of \(3\) or \(5\) in the set of natural numbers below \(1000\) :
Code threes <- 0
fives <- 0
for ( i in 1 : 1000 - 1 ) {
if ( i %% 5 == 0 ) fives <- c ( fives , i )
if ( i %% 3 == 0 ) threes <- c ( threes , i )
}
sum ( unique ( c ( threes , fives ) ) )
Answer 2
Code x <- seq ( 1 , 999 )
sum ( x [ x %% 5 == 0 | x %% 3 == 0 ] )
Python
Answer 1
Code x = []
for i in range (1 , 1000 ):
if (i % 3 == 0 ) or (i % 5 == 0 ):
x.append(i)
sum (x)
Answer 2
Code x = [i for i in range (1 , 1000 ) if (i % 3 == 0 ) or (i % 5 == 0 )]
sum (x)
Back to topReuse © 2023-2026 Vincent Clemson | This post is licensed under <a href='http://creativecommons.org/licenses/by-nc-sa/4.0/' target='_blank'>CC BY-NC-SA 4.0</a>