Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

ค้นหาตัวเลข Armstrong ในช่วงที่กำหนดใน JavaScript


ตัวเลขจะเรียกว่าหมายเลข Armstrong หากสมการต่อไปนี้เป็นจริงสำหรับตัวเลขนั้น:xy...z =xx +yy+...+zz โดยที่ n หมายถึงจำนวนหลักในตัวเลขนั้น

ตัวอย่าง:

153 เป็นหมายเลขอาร์มสตรองเพราะ −

11 +55 +33 = 1 + 125 + 27 =153

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขสองตัว คือช่วง และส่งกลับตัวเลขทั้งหมดระหว่างตัวเลขที่เป็นตัวเลข Armstrong (รวมถึงตัวเลขเหล่านี้ด้วย หากเป็น Armstrong)

ตัวอย่าง

รหัสสำหรับสิ่งนี้จะเป็น −

const isArmstrong = number => {
   let num = number;
   const len = String(num).split("").length;
   let res = 0;
   while(num){
      const last = num % 10;
      res += Math.pow(last, len);
      num = Math.floor(num / 10);
   };
   return res === number;
};
const armstrongBetween = (lower, upper) => {
   const res = [];
   for(let i = lower; i <= upper; i++){
      if(isArmstrong(i)){
         res.push(i);
      };
   };
   return res;
};
console.log(armstrongBetween(1, 400));

ผลลัพธ์

เอาต์พุตในคอนโซล −

[
   1, 2, 3, 4, 5,
   6, 7, 8, 9, 153,
   370, 371
]