태그 보관물: projecteuler

[Python] 6 – Sum square difference

[문제 링크]
http://projecteuler.net/problem=6

[문제 원본]

The sum of the squares of the first ten natural numbers is,

12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

[문제 설명]
1~100까지 합의 제곱 에서 1의 제곱 더하기 2의 제곱 더하기 … 100의 제곱을 더한값을 뺀 값을 구하라.

[소스 코드]

import time
sTime = time.clock()
sqrAndSum = 0
sumAndSqr = 0
for i in range(1, 101):
    sqrAndSum = sqrAndSum + (i*i)

sumAndSqr = 0
for i in range(1, 101):
    sumAndSqr = sumAndSqr + i
sumAndSqr = (sumAndSqr * sumAndSqr)

print("Result=", sumAndSqr - sqrAndSum, "time=", (time.clock() - sTime) * 100)

[출력 결과]

(‘Result=’, 25164150, ‘time=’, 0.007399999999999768)

[Python] 10-Summation of primes

새벽에 회사에서 하던 주사위 풀이를 하려다 딴길로 빠졌습니다.
갑자기 뜬금 없는 Python 으로 간단한 문제 풀이를 했습니다. 생각보다 실행 시간이 오래 걸리네요.
그리고 문제 출처에 소수에 대한 부분이 많이 나오는거 같아 소수 판별을 함수로 분리 했습니다.

[문제 출처]
http://projecteuler.net/problem=10

[문제 내용]
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

[소스 코드]

#summationOfPrimes.py
import coozplz_math
import time

var  = 2000000
sTime = time.clock()


sum = 0
for i in range(2, var-1):
	if(coozplz_math.isPrime(i)) :
		#print("PrimeNumber=", i)
		sum = sum + i
		
eTime = time.clock()
print("input = ", var, " sum =", sum, "time=", (eTime-sTime) * 100, "ms")		

		

#coozplz_math.py
import math

def isPrime(n):	
	result = True
	for i in range(2, int(math.sqrt(n)) + 1):
		if n%i == 0:
			result = False
			break
	
	return result

[출력 결과]
input = 20000 sum = 21171191 time= 6.096835393639568 ms
input = 200000 sum = 1709400814 time= 108.15298899502284 ms
input = 2000000 sum = 142913828922 time= 2501.15873463776 ms