10보다 작은 자연수 중에서 3 또는 5의 배수는 3, 5, 6, 9 이고, 이것을 모두 더하면 23입니다.
1000보다 작은 자연수 중에서 3 또는 5의 배수를 모두 더하면 얼마일까요?
http://projecteuler.net Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
numbers=range(1, 1000) | |
multiple3=set() | |
multiple5=set() | |
for n in numbers: | |
t=divmod(n, 3)[1] | |
if t == 0: | |
multiple3.add(n) | |
t=divmod(n, 5)[1] | |
if t == 0: | |
multiple5.add(n) | |
result=0 | |
for n in multiple3: | |
result = result + n | |
for n in multiple5: | |
result = result + n | |
intersectionNumbers=multiple3.intersection(multiple5) | |
for n in intersectionNumbers: | |
result = result - n | |
print result | |
# 다른사람의 코드 | |
print sum([x for x in range(1, 1000) if x % 3 == 0 or x % 5 == 0]) |
이걸 좀 더 수학적으로 풀어놓은 어느분의 코드를 보니..아래와 같이 변경되더라..
3의배수 + 5의 배수 - 15의배수
흠...
Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
numbers=(1..999) | |
result=0 | |
numbers.each do |number| | |
if number%3 == 0 or number%5 == 0 | |
result = result + number | |
# print number | |
end | |
end | |
puts result | |
# 다른 사람의 솔루션 | |
Array(1..999).inject(0){|a,v| a + ((v%3==0 || v%5==0) ? v : 0)} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use strict; | |
use warnings; | |
my $result=0; | |
for my $num ((1..999)) { | |
if ($num%3 ==0 or $num%5==0) { | |
$result+=$num; | |
} | |
} | |
print $result; |