darrellp

DigitSums

Feb 5th, 2022 (edited)
1,026
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.73 KB | None | 0 0
  1. static class SumFinder
  2. {
  3.     static Dictionary<(int, int), long> record = new Dictionary<(int, int), long>();
  4.  
  5.     public static long CountSums(int n)
  6.     {
  7.         long ret = 0;
  8.         for (int iLength = 1; iLength <= n; iLength++)
  9.         {
  10.             ret += CountSums(iLength, n);
  11.         }
  12.         return ret;
  13.     }
  14.  
  15.     public static long CountSums(int length, int n)
  16.     {
  17.         if (n <= 0 || length < (n + 8) / 9)
  18.         {
  19.             return 0;
  20.         }
  21.         if (length == 1)
  22.         {
  23.             return 0 < n && n < 10 ? 1 : 0;
  24.         }
  25.         if (record.ContainsKey((length, n)))
  26.         {
  27.             return record[(length, n)];
  28.         }
  29.  
  30.         long total = 0;
  31.  
  32.         for (int iLastDigit = 1; iLastDigit < 10; iLastDigit++)
  33.         {
  34.             total += CountSums(length - 1, n - iLastDigit);
  35.         }
  36.         record[(length, n)] = total;
  37.         return total;
  38.     }
  39. }
Add Comment
Please, Sign In to add comment