O primeiro problema do site é bem simples e acredito que muitos já fizeram scripts parecidos na faculdade. O objetivo é retornar a soma de todos os números múltiplos de 3 ou 5.
Multiples of 3 and 5Link para a pergunta: https://projecteuler.net/problem=1
Problem 1
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.
Script que criei para resolver o problema:
soma = 0 for x in range(1,1000): if (x % 3 == 0) or (x % 5 == 0): soma += x print(soma)
Resposta (answer) - Selecione a linha abaixo para ver a resposta
233168
Devemos ficar atento a condição que indica que o número pode ser divisível por 3 OU 5.
A instrução "for x in range(1,1000)" faz como se fosse um while e a variável x vai tendo seu valor acrescido em 1 cada vez que faz o loop até o número 999. Quando atinge o valor 1000 o programa sai do loop. Se eu desejasse que o número 1000 também entrasse na verificação eu teria que escrever a instrução for da seguinte forma: "for x in range(1,1001)".
Segue abaixo algumas outras soluções postadas no fórum:
Usuário: galah92
def serie_sum(diff, limit):
""" Calculate the sum of all numbers divisible by diff up to the limit.
Using the formula of sum of an arithemetic serie (Sn = n*(A1+An)/2),
and the formula to the An term (An = A1+(n-1)*d), combinig our special case
where A1 = d, we can derive our expression.
Args:
diff: plays as 'A1' and 'd' according to the formula.
limit: biggest 'An' to reach to according to the formula.
Returns:
The sum of all numbers divisible by diff up to the limit.
"""
return diff * (limit/diff) * (limit/diff+1) / 2
def main():
""" If we calculate the sum of the numbers divisible by 3 and 5 seperately,
we need to substract the sum of the numbers that are divisible by 15
because they were counted twice.
"""
print serie_sum(3, 999) + serie_sum(5, 999) - serie_sum(15, 999)
if __name__ == '__main__':
main()
Resposta em uma linha do usuário cromod
print sum( val for val in range(1000) if val%3==0 or val%5==0 )
Nenhum comentário:
Postar um comentário