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 specific digits used in squares of numbers using JavaScript
We need to write a JavaScript function that takes an integer n (n >= 0) and a digit d (0
Problem Breakdown
For example, if n = 25 and d = 1, we need to:
- Square all numbers from 0 to 25: 0², 1², 2², ..., 25²
- Count occurrences of digit "1" in all these squares
- Return the total count
Solution
const n = 25;
const d = 1;
const countDigits = (n, d) => {
let k = 0, count = 0;
d = d.toString();
while (k <= n) {
let a = 0;
let s = (k * k).toString();
for (let i = 0; i < s.length; i++) {
if (s[i] == d) {
a++;
}
}
if (a > 0) {
count += a;
}
k++;
}
return count;
};
console.log(countDigits(n, d));
11
How It Works
The function works by:
- Converting the target digit to a string for comparison
- Iterating through all numbers from 0 to n
- Squaring each number and converting to string
- Counting occurrences of the target digit in each square
- Accumulating the total count
Example Walkthrough
// Let's trace through a smaller example: n = 5, d = 1
const traceExample = (n, d) => {
console.log(`Finding digit ${d} in squares from 0² to ${n}²:`);
for (let k = 0; k <= n; k++) {
const square = k * k;
const squareStr = square.toString();
const occurrences = squareStr.split(d.toString()).length - 1;
if (occurrences > 0) {
console.log(`${k}² = ${square} contains ${occurrences} occurrence(s) of ${d}`);
}
}
};
traceExample(5, 1);
Finding digit 1 in squares from 0² to 5²: 1² = 1 contains 1 occurrence(s) of 1 4² = 16 contains 1 occurrence(s) of 1
Optimized Version
const countDigitsOptimized = (n, d) => {
let count = 0;
const digitStr = d.toString();
for (let k = 0; k <= n; k++) {
const square = (k * k).toString();
for (let char of square) {
if (char === digitStr) {
count++;
}
}
}
return count;
};
console.log("Original result:", countDigits(25, 1));
console.log("Optimized result:", countDigitsOptimized(25, 1));
Original result: 11 Optimized result: 11
Conclusion
This function efficiently counts specific digits in squared numbers by converting each square to a string and iterating through its characters. The optimized version eliminates unnecessary variables while maintaining the same functionality.
Advertisements
