python - Sum of all the multiples of 3 or 5 below 1000 -


beginner here- trying make simple python program compute/answer problem:

if list natural numbers below 10 multiples of 3 or 5, 3, 5, 6 , 9. sum of these multiples 23.

find sum of multiples of 3 or 5 below 1000.

currently have:

a = 0 b = 0 while < 1000:     = + 3     print (a)  while b < 1000     b = b + 5     print (b) 

this print numbers being considered. need add them , that's answer.

i 1 of 2 things happen, instead of code have written:

  1. i of happen internally, , therefore not have use "print" function. print sum of of multiples.
  2. i of stuff print, want able print sum of of them too. there way make computer take value of has printed?

actually problem can solved in o(1) instead of o(n) without using loops or lists: required sum sum of multiples of 3 plus sum of multiples of 5 minus sum of multiples of (3*5=15) below given number 1000 (n=999). sums calculated sum of arithmetic series. can calculated in following way:

n=999  # upper bounds arithmetic series upperforthree = n // 3 upperforfive = n // 5 upperforfifteen = n // 15  #calculate sums sumthree = 3*upperforthree*(1 + upperforthree) / 2 sumfive = 5*upperforfive*(1 + upperforfive) / 2 sumfifteen = 15*upperforfifteen*(1 + upperforfifteen) / 2  #calculate total total = sumthree + sumfive - sumfifteen  #print result print(total) 

the result is:

>>>  233168.0 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -