Chúng tôi bắt buộc phải viết một hàm JavaScript lấy một số, chẳng hạn như n, làm đầu vào duy nhất.
Hàm nên -
-
Tính tổng bình phương của n số tự nhiên đầu tiên.
-
Tính bình phương tổng của n số tự nhiên đầu tiên.
-
Trả lại sự khác biệt tuyệt đối giữa cả hai số liệu thu được.
Ví dụ:Nếu n =5;
Sau đó,
sum of squares = 1 + 4 + 9 + 16 + 25 = 55 square of sums = 15 * 15 = 225
Do đó, sản lượng =225 - 55 =170
Ví dụ
Mã cho điều này sẽ là -
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)); Đầu ra
Và đầu ra trong bảng điều khiển sẽ là -
0 170 2640 13160