하나의 유일한 입력으로 n과 같은 숫자를 사용하는 JavaScript 함수를 작성해야 합니다.
함수는 -
-
처음 n개의 자연수의 제곱합을 계산합니다.
-
처음 n개의 자연수의 합계의 제곱을 계산합니다.
-
얻은 두 수치의 절대차를 반환합니다.
예:n =5인 경우
그런 다음
sum of squares = 1 + 4 + 9 + 16 + 25 = 55 square of sums = 15 * 15 = 225
따라서 출력 =225 - 55 =170
예시
이에 대한 코드는 -
const squareDifference = (num = 1) => {
let x = 0;
let y = 0;
let i = 0;
let j = 0;
// function to compute the sum of squares
(function sumOfSquares() {
while (i <= num) {
x += Math.pow(i, 2);
i++;
}
return x;
}());
// function to compute the square of sums
(function squareOfSums() {
while (j <= num) {
y += j;
j++;
}
y = Math.pow(y, 2);
return y;
}());
// returning the absolute difference
return Math.abs(y − x);
};
console.log(squareDifference(1));
console.log(squareDifference(5));
console.log(squareDifference(10));
console.log(squareDifference(15)); 출력
콘솔의 출력은 -
0 170 2640 13160