data-structures · intermediate · ~15 min
Count dice rolls that hit a target sum.
Implement:
long long count_dice_sum(int dice, int faces, int target);
Return the number of ways dice dice, each showing 1..faces, can sum to target.
dice >= 0, faces >= 1, target.
Number of ways.
Sums below dice or above dice*faces are impossible.
#include <stddef.h>
/* Number of ways `dice` dice (each showing 1..faces) can sum to target. dice>=0, faces>=1. */
long long count_dice_sum(int dice,int faces,int target){ (void)dice;(void)faces;(void)target; return 0; }
Naive recursion over faces^dice is too slow; bound the reachable sums.
0 dice hit target 0 in exactly 1 way.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.