Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Counting prime numbers that reduce to 1 within a range using JavaScript
Problem
We need to write a JavaScript function that takes a range array of two numbers and returns the count of prime numbers whose squared sum of digits eventually reduces to 1 through repeated calculation.
For example, 23 is a prime number and:
2² + 3² = 4 + 9 = 13 1² + 3² = 1 + 9 = 10 1² + 0² = 1 + 0 = 1
Since the process eventually reaches 1, the number 23 qualifies as a "happy prime".
Understanding the Solution
The solution involves three key functions:
- isPrime() - Checks if a number is prime
- desiredSeq() - Checks if a number reduces to 1 through digit squaring
- countDesiredPrimes() - Counts qualifying primes in the range
Complete Implementation
const range = [2, 212];
// Extend String prototype to use Array.reduce
String.prototype.reduce = Array.prototype.reduce;
// Function to check if a number is prime
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;
}
// Function to check if number reduces to 1
const desiredSeq = (n) => {
let seen = [n];
while (seen.indexOf(n) === seen.length - 1 && n !== 1) {
// Calculate sum of squares of digits
n = Number(String(n).reduce((acc, digit) => acc + digit * digit, 0));
seen.push(n);
}
return n === 1;
}
// Main function to count desired primes in range
const countDesiredPrimes = ([start, end]) => {
let count = 0;
for (let i = start; i < end; i++) {
if (isPrime(i) && desiredSeq(i)) {
count++;
}
}
return count;
}
console.log(countDesiredPrimes(range));
12
How It Works
The algorithm works in these steps:
- Prime Check: Uses an optimized primality test that checks divisibility up to ?n
- Digit Square Sum: Converts number to string, then calculates sum of squared digits
- Cycle Detection: Tracks seen numbers to detect if the process reaches 1 or enters a cycle
- Range Processing: Iterates through the range and counts numbers that are both prime and "happy"
Example Walkthrough
Let's trace through number 23:
// Step-by-step trace for 23
let n = 23;
console.log(`Starting with: ${n}`);
// First iteration: 2² + 3² = 4 + 9 = 13
n = 2*2 + 3*3;
console.log(`2² + 3² = ${n}`);
// Second iteration: 1² + 3² = 1 + 9 = 10
n = 1*1 + 3*3;
console.log(`1² + 3² = ${n}`);
// Third iteration: 1² + 0² = 1 + 0 = 1
n = 1*1 + 0*0;
console.log(`1² + 0² = ${n}`);
console.log(`Final result: ${n === 1 ? 'Happy number!' : 'Not happy'}`);
Starting with: 23 2² + 3² = 13 1² + 3² = 10 1² + 0² = 1 Final result: Happy number!
Key Points
- The algorithm combines prime number detection with "happy number" verification
- Happy numbers eventually reduce to 1 through repeated digit square sums
- Cycle detection prevents infinite loops for unhappy numbers
- The range [2, 212] contains 12 such prime numbers
Conclusion
This solution efficiently finds prime numbers that are also happy numbers within a given range. The combination of optimized prime checking and cycle detection makes it suitable for processing larger ranges while avoiding infinite loops.
Advertisements
