- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Difference between product and sum of digits of a number in JavaScript
We are required to write a JavaScript function that takes in an positive integer as the only argument.
The function should first count the sum of the digits of the number and then their product. Finally, the function should return the absolute difference of the product and the sum.
For example −
If the input number is −
const num = 12345;
Then the output should be −
const output = 105;
Example
Following is the code −
const num = 12345; const product = (num, res = 1) => { if(num){ return product(Math.floor(num / 10), res * (num % 10)); } return res; }; const sum = (num, res = 0) => { if(num){ return sum(Math.floor(num / 10), res + (num % 10)); } return res; }; const productSumDifference = (num = 1) => { return Math.abs(product(num) - sum(num)); }; console.log(productSumDifference(num));
Output
Following is the console output −
105
Advertisements