fork download
  1. #include<stdio.h>
  2.  
  3. unsigned array[31][20] = {0};
  4.  
  5. //Calc value of num, where num = original_num divided by 2 for nthDiv2 times, and by 3 for nthDiv3 times
  6. unsigned value(unsigned num, unsigned nthDiv2, unsigned nthDiv3)
  7. {
  8. // if value of n when divided by nthDiv2 and nthDiv3 is already calculated just return it from table
  9. if (array[nthDiv2][nthDiv3] != 0)
  10. return array[nthDiv2][nthDiv3];
  11. // Base case - If trying to calculate value of number smaller than 12, return num
  12. else if (num < 12)
  13. return num;
  14.  
  15. // notice that for all numbers >= 12, dividing the coin is better strategy than keeping it as it is
  16. // else - calculate the value we can get by splitting the coin into the coins num/2, num/3, and num/4
  17. else {
  18. unsigned result = value(num/2, nthDiv2+1, nthDiv3) +
  19. value(num/3, nthDiv2, nthDiv3+1) + value(num/4, nthDiv2+2, nthDiv3);
  20. // Memoize result - save it to our array, so we won't have to recompute it
  21. array[nthDiv2][nthDiv3] = result;
  22. return result;
  23. }
  24. }
  25.  
  26. int main(void) {
  27. unsigned original_num = 0;
  28. while (scanf("%u", &original_num) != EOF) {
  29. for (char i = 0; i < 31; i++)
  30. for (char j = 0; j < 20; j++)
  31. array[i][j] = 0;
  32. printf("%u\n", value(original_num, 0, 0));
  33. }
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0s 4232KB
stdin
Standard input is empty
stdout
Standard output is empty