
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting Prime Numbers that Reduce to 1 within a Range Using JavaScript
Problem
We are required to write a JavaScript function that takes in a range array of two numbers. Our function should return the count of such prime numbers whose squared sum of digits eventually yields 1.
For instance, 23 is a prime number and,
22 + 32 = 13 12 + 32 = 10 12 + 02 = 1
Hence, 23 should be a valid number.
Example
Following is the code −
const range = [2, 212]; String.prototype.reduce = Array.prototype.reduce; const isPrime = (n) => { if ( n<2 ) return false; if ( n%2===0 ) return n===2; if ( n%3===0 ) return n===3; for ( let i=5; i*i<=n; i+=4 ) { if ( n%i===0 ) return false; i+=2; if ( n%i===0 ) return false; } return true; } const desiredSeq = (n) => { let t=[n]; while ( t.indexOf(n)===t.length-1 && n!==1 ) t.push(n=Number(String(n).reduce( (acc,v) => acc+v*v, 0 ))); return n===1; } const countDesiredPrimes = ([a, b]) => { let res=0; for ( ; a<b; a++ ) if ( isPrime(a) && desiredSeq(a) ) res++; return res; } console.log(countDesiredPrimes(range));
Output
12
Advertisements