Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ความต่างระหว่างผลรวมกำลังสองกับกำลังสองของผลรวมใน JavaScript

เราต้องเขียนฟังก์ชันที่รับตัวเลข n คำนวณ: 1) ผลรวมของกำลังสองของจำนวนธรรมชาติ 1 ถึง n 2) กำลังสองของผลรวมของจำนวนธรรมชาติ 1 ถึง n 3) คืนความต่างสัมบูรณ์ระหว่างทั้งสอง

ตัวอย่าง: n=5 → sum of squares = 55, square of sums = 225 → diff = 170

ตัวอย่างโค้ด

const squareDifference = (num = 1) => {
  let x = 0, y = 0, i = 0, j = 0;
  (function sumOfSquares() { while (i <= num) { x += Math.pow(i, 2); i++; } return x; }());
  (function squareOfSums() { while (j <= num) { y += j; j++; } y = Math.pow(y, 2); return y; }());
  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