- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Representing number as the power and product of primes in JavaScript
Problem
We are required to write a JavaScript function that takes in a positive integer. Our function should represent this number as the sum of some powers of prime numbers.
Therefore, for the number n, our function should return a string like this −
n = "(p1**n1)(p2**n2)...(pk**nk)"
Where p1, p2, p3..pk are prime numbers and n1, n2,..nk are their non-negative powers and a ** b stands for a raised to the power b.
Example
Following is the code −
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));
Output
(2**5)(5)(7**2)(11)
- Related Articles
- Compare two objects in JavaScript and return a number between 0 and 100 representing the percentage of similarity
- Finding product of Number digits in JavaScript
- Nearest power 2 of a number - JavaScript
- Difference between product and sum of digits of a number in JavaScript
- How to get the exponent power of a number in JavaScript?
- Representing seconds in HH:MM:SS in JavaScript
- Product of two number using HOC - JavaScript
- Find the Number of Primes In A Subarray using C++
- Show that the number 336 and 275 are co primes
- Show that the number 243 and 512 are co-primes
- AND product of arrays in JavaScript
- Count number of primes in an array in C++
- Product sum difference of digits of a number in JavaScript
- Checking if a number is some power of the other JavaScript
- Round number down to nearest power of 10 JavaScript

Advertisements