-1

I'm not sure why this code is giving the error :(

f[0] = 0; 
f[n_] := f[n] = DigitCount[n, 10, 1] + f[n - 1];
f[1016]

enter image description here

Raksha
  • 633
  • 1
  • 6
  • 19
  • It's not. You probably have leftover definitions. ClearAll[f] then try again. – Szabolcs Mar 02 '15 at 20:09
  • still same error :( – Raksha Mar 02 '15 at 20:19
  • What precise version of Mathematica are you using? Have you tried restarting Mathematica? If all this doesn't help, please restart Mathematica, try it again in a new notebook, and make a screenshot of the notebook (with code and error), then post it. – Szabolcs Mar 02 '15 at 20:19
  • picture posted. – Raksha Mar 02 '15 at 20:26
  • This code was not run immediately after restarting Mathematica so we have no way of knowing what may have been evaluated before. Do not rely on clearing the Global context, please restart Mathematica fully, make sure there's only a single notebook open, and do this again. It's clear that the factor causing the problem is something you do not expect, so don't make assumptions about what is a sufficient substitute for restarting. – Szabolcs Mar 02 '15 at 20:37
  • 1
    Szabolcs is right. f[1016] is 326. – bill s Mar 02 '15 at 20:41
  • 2
    Another thing I just noticed is that your screenshot has 1050, which is greater than 1024, while in the code you posted there's 1016. It is true that f[1050] will cause Mathematica to exceed the recursion limit. You can increase $RecursionLimit to solve this. f[1016] should not trigger the error. – Szabolcs Mar 02 '15 at 20:57
  • the screenshot has 1050 because after restarting Mathematica, it ran 1016 fine, so I increased it to see if it works for all number now, but it broke at 1050. Is this really the limit for it? I'm afraid to increase recursion limit because Mathematica regularly freezes my laptop, even when I use "MemoryConstrained[ , (1024^3)]" I was hoping to be able to get to much higher numbers with that function... – Raksha Mar 02 '15 at 21:05
  • 3
    @Solarmew Block[{$RecursionLimit = 10^6}, f[5000]] for example. You need to understand what "recursion limit" means - the default recursion limit is 1024 and if you truly understood the limit you would realize that you have to increase it if you want evaluate the function for higher numbers. – C. E. Mar 02 '15 at 21:45

1 Answers1

4

Just a suggestion. Try to use tail recursion to free the stack.

ClearAll[f,g];
g[n_] := g[n] = f[n, 0]
f[0, x_] := x;
f[n_, upto_] := f[n - 1, upto + DigitCount[n, 10, 1]]
g[2000]
(*1600*)
Dr. belisarius
  • 115,881
  • 13
  • 203
  • 453