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
Finding lunar sum of Numbers - JavaScript
The concept of lunar sum says that the sum of two numbers is calculated by taking the larger digit from each corresponding position, instead of adding them together.
How Lunar Sum Works
For each digit position, we compare the digits from both numbers and take the maximum value. Let's see how this works with an example:
a = 879 and b = 768
Position-wise comparison:
Position 1: max(8, 7) = 8 Position 2: max(7, 6) = 7 Position 3: max(9, 8) = 9 Lunar Sum: 879
Implementation
Here's a JavaScript function that calculates the lunar sum of two numbers:
const num1 = 6565;
const num2 = 7385;
const lunarSum = (num1, num2) => {
const numStr1 = String(num1);
const numStr2 = String(num2);
let res = 0, temp;
for(let i = 0; i < numStr1.length; i++){
temp = Math.max(+numStr1[i], +numStr2[i]);
res = (res * 10) + temp;
}
return res;
};
console.log(lunarSum(num1, num2));
7585
Step-by-Step Breakdown
Let's trace through the example with numbers 6565 and 7385:
const num1 = 6565;
const num2 = 7385;
const lunarSumDetailed = (num1, num2) => {
const numStr1 = String(num1);
const numStr2 = String(num2);
let res = 0;
console.log(`Comparing ${num1} and ${num2}:`);
for(let i = 0; i < numStr1.length; i++){
const digit1 = +numStr1[i];
const digit2 = +numStr2[i];
const maxDigit = Math.max(digit1, digit2);
console.log(`Position ${i + 1}: max(${digit1}, ${digit2}) = ${maxDigit}`);
res = (res * 10) + maxDigit;
}
return res;
};
console.log("Result:", lunarSumDetailed(num1, num2));
Comparing 6565 and 7385: Position 1: max(6, 7) = 7 Position 2: max(5, 3) = 5 Position 3: max(6, 8) = 8 Position 4: max(5, 5) = 5 Result: 7585
Alternative Implementation
Here's another approach using array methods:
const lunarSumArray = (num1, num2) => {
const digits1 = String(num1).split('').map(Number);
const digits2 = String(num2).split('').map(Number);
const result = digits1.map((digit, index) =>
Math.max(digit, digits2[index])
).join('');
return parseInt(result);
};
console.log(lunarSumArray(6565, 7385));
console.log(lunarSumArray(1234, 5678));
console.log(lunarSumArray(9999, 1111));
7585 5678 9999
Key Points
- Lunar sum compares digits position-wise and takes the maximum
- Both numbers should have the same number of digits for this implementation
- The result always has digits that are greater than or equal to both input numbers at each position
- This operation is not commutative in the traditional sense, but the result is the same regardless of parameter order
Conclusion
Lunar sum provides an interesting alternative to traditional addition by taking the maximum digit at each position. This technique can be useful in certain mathematical applications and algorithmic problems.
