  Programming Questions

• Popular Tags
• Additive Persistence Problem
Hello. I'm finding myself stuck on a problem, and this is probably an easy thing to fix for most, but I just can't figure out my mistake in this case. That in mind: if someone could please help me out, it would certainly save me hours more of struggle, and I'd really appreciate it. The Challenge: I'm trying to find the Additive Persistence of a number (ie, 4321 = 10 = 1, ergo its A.P. is "2", as this result required two iterations in order to transform the original number into a single digit.) The Problem: My code gets through two iterations (eg, 4-3-2-1=10=1), but then ends abruptly. It loads the recursive function one time, and on this second iteration, it fails after the for loop. The length is 1 so it should trigger the else statement, but does not. I checked and the length is indeed 1, yet the program fails to recognize this as I stated. However, the other problem is that if I were to enter in a large enough starting number to the point that it required more than 2 iterations to find the A.P. (eg, '9999999999999999999'), then it crashes on the first iteration. What am I doing wrong here? Please? var num = 9999999; //console.log(num); var counter = 0; //console.log(spl); function findAdd (num){ counter++; var res = 0; var spl = num.toString(10).split(""); console.log(spl); //console.log(spl.length + " len"); //console.log(res +" res"); //=10 //console.log(res.toString().length +" len"); //=2 for (var n = 0; n < spl.length; n++) { res += parseInt(spl[n],10); console.log(res); } if (res.toString().length > 1) { //counter++; console.log(counter + " counter"); findAdd(parseInt(res,10)); } else { return counter + " FINAL ANSWER"; } } findAdd(num); nytek posted this question on 9/13/15 |