Created
September 14, 2019 08:46
-
-
Save nkgokul/1d0664d6e9e1b3c4ab3a121e50524dce to your computer and use it in GitHub Desktop.
Recursive Digit Sum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
function recuresiveSum(number){ | |
finalRecursiveSum = 0; | |
while(number){ | |
digit = number % 10; | |
finalRecursiveSum += digit; | |
if (finalRecursiveSum>9) finalRecursiveSum -=9; | |
number = (number-digit)/10 | |
} | |
return (finalRecursiveSum); | |
} | |
function runTestforFixedValues() { | |
fixedValues = [0,1,10,123,999,1000,123456789]; | |
fixedValues.map(function(number){ | |
console.log("" + number + "-----" +recuresiveSum(number)); | |
}); | |
} | |
function runTestforRandom() { | |
randomValues = []; | |
max = 10000; | |
number = getRandomNumber(1,max); | |
console.log("" + number + "-----" +recuresiveSum(number)); | |
} | |
function runTests() { | |
console.log("==========================================="); | |
console.log("Running Tests for Fixed Values\n"); | |
runTestforFixedValues(); | |
console.log("\nRunning Tests for \n"); | |
loop(runTestforRandom, 10); | |
} | |
function getRandomNumber(start = 1, end = 10) { | |
if (start > end) { | |
[start, end] = [end, start]; | |
} | |
let range = end - start + 1; | |
return (parseInt(Math.random() * range) % range) + start; | |
} | |
const loop = (fn, times = 5, params = []) => { | |
if (!times) { | |
return; | |
} | |
fn(...params); | |
loop(fn, times - 1, params); | |
}; | |
runTests(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment