Print ways to obtain given sum by repeated throws of a dice - GeeksforGeeks

12 Jan, 2022
Given an integer N, the task is to print the ways to get the sum N by repeatedly throwing a dice.
Input: N = 3Output: 1 1 11 22 13Explanation: The standard dice has 6 faces i.e, {1, 2, 3, 4, 5, 6}. Therefore the ways of getting sum 3 after repeatedly throwing a dice are as follows:1 + 1 + 1 = 31 + 2 = 32 + 1 = 33 = 3
Input: N = 2Output: 1 12
Approach: This problem can be solved by using Recursion and Backtracking. The idea is to iterate for every possible value of dice i in the range [1, 6] and recursively call for the remaining sum i.e, (N – i) and keep appending the value of the current dice value in a data structure like strings. If the required sum is zero, print the elements in the stored string.
Below is the implementation of the above approach
C++
Java
Python3
C#
Javascript
// C++ program of the above approach#include <iostream>using namespace std; // Recursive function to print the// number of ways to get the sum// N with repeated throw of a dicevoid printWays(int n, string ans){    // Base Case    if (n == 0) {         // Print characters in        // the string        for (auto x : ans) {            cout << x << " ";        }        cout << endl;        return;    }     // If n is less than zero,    // no sum is possible    else if (n < 0) {        return;    }     // Loop to iterate over all    // the possible current moves    for (int i = 1; i <= 6; i++) {         // Recursive call for the        // remaining sum considering        // i as the current integer        printWays(n - i, ans + to_string(i));    }} // Driver Codeint main(){    int N = 3;    printWays(N, "");    return 0;}
// Java program for the above approachimport java.util.*;public class GFG {     // Recursive function to print the// number of ways to get the sum// N with repeated throw of a dicestatic void printWays(int n, String ans){       // Base Case    if (n == 0) {         // Print characters in        // the string        for (int i = 0; i < ans.length(); i++) {            System.out.print(ans.charAt(i) + " ");        }        System.out.println();        return;    }     // If n is less than zero,    // no sum is possible    else if (n < 0) {        return;    }     // Loop to iterate over all    // the possible current moves    for (int i = 1; i <= 6; i++) {         // Recursive call for the        // remaining sum considering        // i as the current integer        printWays(n - i, ans + Integer.toString(i));    }} // Driver Codepublic static void main(String args[]){    int N = 3;    printWays(N, ""); }} // This code is contributed by Samim Hossain Mondal.
# Python code for the above approach # Recursive function to print the# number of ways to get the sum# N with repeated throw of a dicedef printWays(n, ans):     # Base Case    if n == 0:         # Print characters in        # the string        for x in range(len(ans)):            print(ans[x], end=" ")        print("")        return     # If n is less than zero,    # no sum is possible    elif n < 0:        return     # Loop to iterate over all    # the possible current moves    for i in range(1, 7):         # Recursive call for the        # remaining sum considering        # i as the current integer        printWays(n - i, ans + str(i)) # Driver CodeN = 3printWays(N, "") # This code is contributed by gfgking
// C# program for the above approachusing System;using System.Collections; class GFG {   // Recursive function to print the  // number of ways to get the sum  // N with repeated throw of a dice  static void printWays(int n, string ans)  {     // Base Case    if (n == 0) {       // Print characters in      // the string      for (int i = 0; i < ans.Length; i++) {        Console.Write(ans[i] + " ");      }      Console.WriteLine();      return;    }     // If n is less than zero,    // no sum is possible    else if (n < 0) {      return;    }     // Loop to iterate over all    // the possible current moves    for (int i = 1; i <= 6; i++) {       // Recursive call for the      // remaining sum considering      // i as the current integer      printWays(n - i, ans + i.ToString());    }  }   // Driver Code  public static void Main()  {    int N = 3;    printWays(N, "");   }} // This code is contributed by Samim Hossain Mondal.
<script>      // JavaScript code for the above approach       // Recursive function to print the      // number of ways to get the sum      // N with repeated throw of a dice      function printWays(n, ans)      {                 // Base Case          if (n == 0) {               // Print characters in              // the string              for (let x = 0; x < ans.length; x++) {                  document.write(ans[x] + " ");              }              document.write('<br>')              return;          }           // If n is less than zero,          // no sum is possible          else if (n < 0) {              return;          }           // Loop to iterate over all          // the possible current moves          for (let i = 1; i <= 6; i++) {               // Recursive call for the              // remaining sum considering              // i as the current integer              printWays(n - i, ans + (i).toString());          }      }       // Driver Code      let N = 3;      printWays(N, ""); // This code is contributed by Potta Lokesh  </script>
1 1 1 
1 2 
2 1 
3 
Time Complexity: O(6N)Auxiliary Space: O(1)
lokeshpotta20
samim2000
gfgking
sagartomar9927
Algo-Geek 2021
Permutation and Combination
Algo Geek
Backtracking
Recursion
Recursion
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Minimize cost to sort given array by sorting unsorted subarrays
Program to find simple moving average | Set-2
Divide given number into two even parts
Check if the given string is valid English word or not
Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index
N Queen Problem | Backtracking-3
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
The Knight's tour problem | Backtracking-1
Sudoku | Backtracking-7