이경수 선생님의 수학실험실

Problem 6(Sum square difference) 본문

Project Euler

Problem 6(Sum square difference)

(이경수) 2019. 2. 8. 20:10

Problem 6(Sum square difference)

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.



In Python:

def sum_squre(n):
result=0
for i in range(1, n+1):
result+=pow(i,2)
return result

def squre_sum(n):
sum=0
for i in range(1,n+1):
sum+=i
result=pow(sum,2)
return result

print(squre_sum(100)-sum_squre(100))


In Java:

//Euler6 Sum square difference

package project_euler;


public class Euler6 {

public static int sumSqure(int n) {

int result = 0;

for (int i = 1; i < n + 1; i++) {

result += Math.pow(i, 2);

}

return result;

}

public static double squreSum(int n) {

int sum = 0;

double result = 0;

for (int i = 1; i < n + 1; i++) {

sum += i;

result = Math.pow(sum, 2);

}

return result;

}

public static void main(String[] args) {

long startTime = System.currentTimeMillis();

System.out.println(squreSum(100) - sumSqure(100));

long endTime = System.currentTimeMillis();

System.out.println((double)(endTime - startTime) / (double)1000 + "seconds");

}

}


Run time: 0.002seconds


solution: 25164150


[from Project Euler: https://projecteuler.net/problem=6]



'Project Euler' 카테고리의 다른 글

Problem 8(Largest product in a series)  (0) 2019.02.09
Problem 7(10001st prime)  (0) 2019.02.08
Problem 5(Smallest multiple)  (0) 2019.02.08
Problem 4(Largest palindrome product)  (0) 2019.02.07
Problem 3(Largest prime factor)  (0) 2019.02.06
Comments