Skip to content

Instantly share code, notes, and snippets.

@vivanov1410
Last active December 16, 2015 15:39
Show Gist options
  • Select an option

  • Save vivanov1410/5457539 to your computer and use it in GitHub Desktop.

Select an option

Save vivanov1410/5457539 to your computer and use it in GitHub Desktop.
solution for tasuku1: "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". answer: 234168, total basic operations = 21
a = 3
b = 5
c = 1000
sum = 0
counter = 0
function foo()
sum = 0
for i = a,c-1 do
if i%a == 0 then
sum = sum+i
counter = counter+1
elseif i%b == 0 then
sum = sum+i
counter = counter+1
end
end
return sum
end
function bar()
-- using sum of arithmetic progression s = n(start + end)/2
-- find sum of all multiples of 3
sum_a = asum(a, c)
-- find sum of all multiples of 5
sum_b = asum(b, c)
-- common multiple 3 and is 15
ab = a*b
-- find sum of all multiples of 15
sum_ab = asum(ab, c)
-- deduct duplicate numbers
counter = counter+3
return sum_a+sum_b-sum_ab
end
-- return sum of arithmetic progression
function asum(delta, limit)
n = math.floor((limit-1)/delta)
counter = counter+6
--return n*(delta + n*delta)*0.5
return n*delta*(n+1)*0.5
end
print("results:")
print("foo = ", foo())
print("total basic operations = ", counter)
counter = 0
print()
print("bar = ", bar())
print("total basic operations = ", counter)
counter = 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment