เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลข เช่น n เป็นอินพุตเดียวและตัวเดียว
ฟังก์ชันควร −
-
คำนวณผลรวมกำลังสองของจำนวนธรรมชาติ 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