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

แสดงตัวเลขเป็นกำลังและผลคูณของจำนวนเฉพาะใน JavaScript


ปัญหา

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่ใช้จำนวนเต็มบวก ฟังก์ชันของเราควรแทนตัวเลขนี้เป็นผลรวมของยกกำลังบางจำนวนเฉพาะ

ดังนั้น สำหรับตัวเลข n ฟังก์ชันของเราควรส่งคืนสตริงเช่นนี้ −

n = "(p1**n1)(p2**n2)...(pk**nk)"

โดยที่ p1, p2, p3..pk เป็นจำนวนเฉพาะ และ n1, n2,..nk เป็นจำนวนยกกำลังที่ไม่เป็นลบ และ a ** b หมายถึง a ยกกำลัง b

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

const isPrime = num => {
    for(let i = 2; i < num; i++){
        if(num % i === 0){
            return false;
        }
    };
    return num > 1;
}
const count = (arr = [], n = 1) => {
for(const k in arr){
    if(n % k === 0){
         arr[k] += 1;
         return count(arr, n / k)
      }
   };
       
   return arr;
};
const primeFactors = (n) => {
    const res = [];
    for(let i = 2; i < n; i++){
        if(isPrime(i)){
            res.push(i);
        }
    };
  const arr = [];
    for(const el in res){
        arr[el] = 0;
    };
    count(arr,n);
    let str = '';
    for(const x in arr){
  if(arr[x] > 1){
         str += '(%s**%s)' %(x,arr[x])
      }else if(arr[x] === 1){
          str += '(%s)' % (x)
      };
  };
   return str
};
console.log(primeFactors(86240));

ผลลัพธ์

(2**5)(5)(7**2)(11)