Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Count different numbers that can be generated such that there digits sum is equal to 'n'
Next article icon

Count different numbers that can be generated such that there digits sum is equal to 'n'

Last Updated : 09 May, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an positive integer n. Count the different numbers that can be generated using digits 1, 2, 3 and 4 such that digits sum is the number 'n'. Here digit '4' will be treated as '1'. For instance, 
32 = 3 + 2 = 5 
1341 = 1 + 3 + 1 + 1 = 6 
441 = 1 + 1 + 1 = 3 
Note: Answer the value in mod = 109+7 

Input: 2 Output: 5 Explanation There are only '5' numbers that can  be made: 11 = 1 + 1 = 2 14 = 1 + 1 = 2 41 = 1 + 1 = 2 44 = 1 + 1 = 2 2  = 2  Input: 3 Output: 13 Explanation There are only '13' numbers that can  be made i.e., 111, 114, 141, 144, 411,  414, 441, 444, 12, 21, 42, 24, 3.

The approach is to use Dynamic programming. The problem is same as coin change and Ways to write n as sum of two or more positive integers problems. The only difference is that, instead of iterating up-to 'n', iterate only from 1 to 3 as according to question, only 1, 2, 3 and 4 digits are allowed. But since '4' can be replaced with '1' therefore iterate through 1, 2 and 3 and double the count of '1' for compensation of digit '4'. 

C++
// C++ program to count ways to write // 'n' as sum of digits #include<iostream> using namespace std;  // Function to count 'num' as sum of // digits(1, 2, 3, 4) int countWays(int num) {     // Initialize dp[] array     int dp[num+1];      const int MOD = 1e9 + 7;     // Base case     dp[1] = 2;      for(int i = 2; i <= num; ++i)     {         // Initialize the current dp[]          // array as '0'         dp[i] = 0;          for(int j = 1; j <= 3; ++j)         {             /* if i == j then there is only                one way to write with element                itself 'i' */             if(i - j == 0)                dp[i] += 1;              /* If j == 1, then there exist                two ways, one from '1' and                other from '4' */             else if (j == 1)                dp[i] += dp[i-j] * 2;              /* if i - j is positive then                pick the element from 'i-j'                element of dp[] array */             else if(i - j > 0)                dp[i] += dp[i-j];          // Check for modulus         if(dp[i] >= MOD)             dp[i] %= MOD;         }      }      // return the final answer     return dp[num]; }  // Driver code int main() {     int n = 3;     cout << countWays(n);          return 0; } 
Java
// Java program to count ways to  // write 'n' as sum of digits import java.io.*;  public class GFG {  // Function to count 'num' as  // sum of digits(1, 2, 3, 4) static int countWays(int num) {          // Initialize dp[] array     int []dp= new int[num + 1];     int MOD = (int)1E9 + 7;          // Base case     dp[1] = 2;      for(int i = 2; i <= num; ++i)     {         // Initialize the current         // dp[] array as '0'          dp[i] = 0;          for(int j = 1; j <= 3; ++j)         {             // if i == j then there is              // only one way to write with             // element itself 'i'             if(i - j == 0)             dp[i] += 1;              // If j == 1, then there exist             // two ways, one from '1' and             // other from '4'              else if (j == 1)                 dp[i] += dp[i - j] * 2;              // if i - j is positive then             // pick the element from 'i-j'             // element of dp[] array              else if(i - j > 0)                 dp[i] += dp[i - j];          // Check for modulus         if(dp[i] >= MOD)             dp[i] %= MOD;         }      }      // return the final answer     return dp[num]; }      // Driver code     static public void main (String[] args)     {         int n = 3;         System.out.println(countWays(n));          } }  // This code is contributed by vt_m 
Python3
# Python3 program to count ways to write  # 'n' as sum of digits   # Function to count 'num' as sum of  # digits(1, 2, 3, 4)  def countWays(num):       # Initialize dp[] array      dp = [0] * (num + 1);       MOD = 100000000 + 7;           # Base case      dp[1] = 2;       for i in range(2, num + 1):                  # Initialize the current dp[]          # array as '0'          dp[i] = 0;           for j in range(1, 4):                           # if i == j then there is only              # one way to write with element              # itself 'i'              if(i - j == 0):                 dp[i] += 1;               # If j == 1, then there exist              # two ways, one from '1' and              # other from '4'             elif (j == 1):                 dp[i] += dp[i - j] * 2;               # if i - j is positive then              # pick the element from 'i-j'              # element of dp[] array              elif(i - j > 0):                 dp[i] += dp[i - j];           # Check for modulus          if(dp[i] >= MOD):              dp[i] %= MOD;       # return the final answer      return dp[num];   # Driver code  n = 3;  print(countWays(n));   # This code is contributed by mits 
C#
// C# program to count ways to  // write 'n' as sum of digits using System;  public class GFG {  // Function to count 'num' as  // sum of digits(1, 2, 3, 4) static int countWays(int num) {          // Initialize dp[] array     int []dp= new int[num + 1];     int MOD = (int)1E9 + 7;          // Base case     dp[1] = 2;      for(int i = 2; i <= num; ++i)     {         // Initialize the current         // dp[] array as '0'          dp[i] = 0;          for(int j = 1; j <= 3; ++j)         {             // if i == j then there is              // only one way to write with             // element itself 'i'             if(i - j == 0)             dp[i] += 1;              // If j == 1, then there exist             // two ways, one from '1' and             // other from '4'              else if (j == 1)                 dp[i] += dp[i - j] * 2;              // if i - j is positive then             // pick the element from 'i-j'             // element of dp[] array              else if(i - j > 0)                 dp[i] += dp[i - j];          // Check for modulus         if(dp[i] >= MOD)             dp[i] %= MOD;         }      }      // return the final answer     return dp[num]; }      // Driver code     static public void Main (String []args)     {         int n = 3;         Console.WriteLine(countWays(n));          } }  // This code is contributed by vt_m 
PHP
<?php // PHP program to count ways to write  // 'n' as sum of digits   // Function to count 'num' as sum of  // digits(1, 2, 3, 4)  function countWays($num)  {      // Initialize dp[] array      $dp[$num + 1] = array();       $MOD = 100000000 + 7;           // Base case      $dp[1] = 2;       for($i = 2; $i <= $num; ++$i)      {          // Initialize the current dp[]          // array as '0'          $dp[$i] = 0;           for($j = 1; $j <= 3; ++$j)          {              /* if i == j then there is only              one way to write with element              itself 'i' */             if($i - $j == 0)              $dp[$i] += 1;               /* If j == 1, then there exist              two ways, one from '1' and              other from '4' */             else if ($j == 1)              $dp[$i] += $dp[$i - $j] * 2;               /* if i - j is positive then              pick the element from 'i-j'              element of dp[] array */             else if($i - $j > 0)              $dp[$i] += $dp[$i - $j];           // Check for modulus          if($dp[$i] >= $MOD)              $dp[$i] %= $MOD;          }      }       // return the final answer      return $dp[$num];  }   // Driver code  $n = 3;  echo countWays($n);   // This code is contributed by jit_t ?> 
JavaScript
<script>  // JavaScript program to count ways to  // write 'n' as sum of digits  // Function to count 'num' as  // sum of digits(1, 2, 3, 4) function countWays(num) {          // Initialize dp[] array     let dp = [];     let MOD = 1E9 + 7;            // Base case     dp[1] = 2;        for(let i = 2; i <= num; ++i)     {                  // Initialize the current         // dp[] array as '0'          dp[i] = 0;            for(let j = 1; j <= 3; ++j)         {                          // If i == j then there is              // only one way to write with             // element itself 'i'             if (i - j == 0)                 dp[i] += 1;                // If j == 1, then there exist             // two ways, one from '1' and             // other from '4'              else if (j == 1)                 dp[i] += dp[i - j] * 2;                // If i - j is positive then             // pick the element from 'i-j'             // element of dp[] array              else if (i - j > 0)                 dp[i] += dp[i - j];                // Check for modulus             if (dp[i] >= MOD)                 dp[i] %= MOD;         }        }          // Return the final answer     return dp[num]; }  // Driver Code let n = 3;  document.write(countWays(n));  // This code is contributed by susmitakundugoaldanga  </script> 

Output 

13


Time complexity: O(n) 
Auxiliary space: O(n)
Note: Asked in Directi coding round(2014 and 2017)
 


Next Article
Count different numbers that can be generated such that there digits sum is equal to 'n'

B

bansal1232
Improve
Article Tags :
  • Misc
  • Mathematical
  • DSA
  • Directi
  • number-digits
Practice Tags :
  • Directi
  • Mathematical
  • Misc

Similar Reads

    Count total number of N digit numbers such that the difference between sum of even and odd digits is 1
    Given a number n, we need to count the total number of n digit numbers such that the sum of even digits is 1 more than the sum of odd digits. Here even and odd means positions of digits are like array indexes, for example, the leftmost (or leading) digit is considered as even digit, next to leftmost
    10 min read
    Count numbers with difference between number and its digit sum greater than specific value
    Given a positive integer n and an integer d, the task is to find the count of numbers smaller than or equal to n such that the difference between the number and sum of its digits is greater than or equal to given difference d. Examples: Input : n = 13, d = 2Output : 4Explanation: 10, 11, 12 and 13 s
    9 min read
    Find a number x such that sum of x and its digits is equal to given n.
    Given a positive number n. We need to find a number x such that sum of digits of x to itself is equal to n. If no such x is possible print -1.Examples: Input : n = 21 Output : x = 15 Explanation : x + its digit sum = 15 + 1 + 5 = 21 Input : n = 5 Output : -1 We iterate from 1 to n and for each inter
    5 min read
    Count of n digit numbers whose sum of digits equals to given sum
    Given two integers n and sum, the task is to find the count of all n digit numbers with sum of digits equal to sum. Note: Leading 0's are not counted as digits. If there exist no n digit number with sum of digits equal to given sum, print -1.Example: Input: n = 2, sum= 2Output: 2Explanation: The num
    15+ min read
    Count numbers (smaller than or equal to N) with given digit sum
    Given a number N and a sum S, find the count of numbers upto N that have digit sum equal to S. Examples: Input : N = 100, S = 4 Output : 5 Upto 100 only 5 numbers(4, 13, 22, 31, 40) can produce 4 as their sum of digits. Input : N = 1000, S = 1 Output : 4 Upto 1000 only 4 numbers(1, 10, 100 and 1000)
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences