// The sum of the squares of the first ten natural numbers is 385.
// The square of the sum of the first ten natural numbers is 3025
// Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 2640
// Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
Question)
-- 1부터 10까지의 자연수에 대하여 각각의 제곱을 더한 값(Sum of the Square)은 385이다.
-- 1부터 10까지의 자연수를 더하여 제곱을 한 값 (Square of the Sum)은 3025이다.
-- Square of the Sum과 Sum of the Square의 차이는 2640이다.
-- 1부터 100까지의 자연수에 대하여 Square of the Sum과 Sum of the Square의 차이를 구하라.
public class ProjectEuler_006 {
public static void main(String[] args) {
int sumOfSquare = 0;
int squareOfSum = 0;
int sum = 0; // 1)
// Sum of Square
for (int i = 0; i <= 100; i++) {
int square = i * i;
sumOfSquare += square; // 2)
}
// Square of Sum
for (int j = 0; j <= 100; j++) {
sum += j;
}
squareOfSum = sum * sum; // 3)
int result = Math.abs(squareOfSum - sumOfSquare); // 4)
System.out.println("The difference between the sum of the square of 1 to 100 and the square of the sum is " + result);
}
}
1) 모든 값을 0으로 초기화해서, 나온 값을 더해주는 방법을 선택함.
2) 1부터 100까지 각각의 제곱 값을 sumOfSquare에 저장함.
3) squareOfSum에 1부터 100까지 더한 값을 제곱한 값을 넣어줌.
4) 차이를 구하는 것이기 때문에 절대값으로 구해준다. (그냥 result만 보여주면 값이 음수가 나올 수 있음.)
'잡다한 코딩 > Project Euler (Java)' 카테고리의 다른 글
| (Java) Project Euler 008 - Largest Product in a Series (0) | 2023.12.17 |
|---|---|
| (Java) Project Euler 007 - 10001st Prime (0) | 2023.12.16 |
| (Java) Project Euler 005 - Smallest Multiple (0) | 2023.12.14 |
| (Java) Project Euler 004 - Largest Palindrome Product (0) | 2023.12.13 |
| (Java) Project Euler 003 - Largest Prime Factor (2) | 2023.12.12 |