Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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:
Find the smallest number whose digits multiply to a given number n
Next article icon

Find M-th number whose repeated sum of digits of a number is N

Last Updated : 02 Feb, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two positive integers N and M, The task is to find the M-th number whose sum of digits of a number until the sum becomes a single digit is N.

Examples: 

Input: N = 1, M = 3
Output: 19 
The first two numbers are 1 and 10.

Input: N = 2, M = 5
Output:  38 
The first four numbers are 2, 11, 20, and 29.

A naive approach is to iterate for all numbers and keep a count of numbers whose sum returns N. 

  • Create a function singleDigit that takes an integer as input, and returns the single-digit number obtained by summing up the digits of the input number and repeating until the sum is a single-digit number.
  • Define a function findMthNum which takes two inputs, N and M
  • Initialize a variable count to 0
  • Initialize a variable i to 1
  • Use while loop, while true
    • calculate the single digit number of i using function singleDigit
    • check if the single-digit number is equal to N, if yes, increment the count by 1
    • check if the count is equal to M, if yes, return i
    • increment i

Below is the implementation of the above approach:

C++
#include <iostream> using namespace std;  // function to calculate the sum of digits of the number int singleDigit(long long n) {     int result;      while (true) {         string s = to_string(n);         int sum = 0;         for (auto i : s)             sum += (i - '0');          if (sum > 9) {             n = sum;         }         else {             result = sum;             break;         }     }     return result; }  int findMthNum(int N, int M) {     int count = 0;     int i = 1;     while (true) {         int sum = singleDigit(i);         if (sum == N) {             count++;         }          if (count == M) {             return i;         }         i++;     } }  int main() {     int N = 2;     int M = 5;     cout << "Mth number whose sum of digits is " << N          << " is : " << findMthNum(N, M);     return 0; } 
Java
import java.io.*; import java.util.*;  public class Gfg {     // function to calculate the sum of digits of the number     public static int singleDigit(long n)     {         int result;          while (true) {             String s = String.valueOf(n);             int sum = 0;             for (int i = 0; i < s.length(); i++) {                 sum += (s.charAt(i) - '0');             }              if (sum > 9) {                 n = sum;             }             else {                 result = sum;                 break;             }         }         return result;     }      public static int findMthNum(int N, int M)     {         int count = 0;         int i = 1;         while (true) {             int sum = singleDigit(i);             if (sum == N) {                 count++;             }              if (count == M) {                 return i;             }             i++;         }     }      public static void main(String[] args)     {         int N = 2;         int M = 5;         System.out.println(             "Mth number whose sum of digits is " + N             + " is : " + findMthNum(N, M));     } } 
Python3
# function to calculate the sum of digits of the number def singleDigit(n):          result = 0      while (1):         s = str(n)         sum = 0         for i in range(0, len(s)):             sum = sum + int(s[i])          if (sum > 9):             n = sum         else:             result = sum             break                  return result  def findMthNum(N, M):          count = 0     i = 1     while (1):         sum = singleDigit(i)         if (sum == N):             count = count + 1          if (count == M):             return i         i = i + 1  N = 2 M = 5 print("Mth number whose sum of digits is ", N, " is : ", findMthNum(N, M));  # The code is contributed by Gautam goel.  
C#
using System;   class HelloWorld {          // function to calculate the sum of digits of the number     public static int singleDigit(int n)     {         int result = 0;          while (true) {             string s = n.ToString();             int sum = 0;             for(int i = 0; i < s.Length; i++){                 sum += (s[i] - '0');             }              if (sum > 9) {                 n = sum;             }             else {                 result = sum;                 break;             }         }         return result;     }          public static int findMthNum(int N, int M)     {         int count = 0;         int i = 1;         while (true) {             int sum = singleDigit(i);             if (sum == N) {                 count = count + 1;             }              if (count == M) {                 return i;             }             i = i + 1;         }     }          static void Main() {         int N = 2;         int M = 5;                  Console.WriteLine("Mth number whose sum of digits is " + N + " is : " + findMthNum(N, M));     } }  // The code is contributed by Gautam goel.  
JavaScript
// function to calculate the sum of digits of the number function singleDigit(n) {     let result;      while (true) {         let s = n.toString();         let sum = 0;         for (let i of s)             sum += parseInt(i);          if (sum > 9) {             n = sum;         }         else {             result = sum;             break;         }     }     return result; }  function findMthNum( N, M) {     let count = 0;     let i = 1;     while (true) {         let sum = singleDigit(i);         if (sum == N) {             count++;         }          if (count == M) {             return i;         }         i++;     } }  let N = 2; let M = 5; console.log("Mth number whose sum of digits is " + N      + " is : " + findMthNum(N, M)); 

Output
Mth number whose sum of digits is 2 is : 38

Time Complexity: O(N*M), where N is the number whose sum of digits is being calculated and M is the number of digits in the input number.
Auxiliary Space: O(1), as it uses only a constant amount of memory.

An efficient approach is to find the summation of digits till it becomes single digits in O(1) which has been discussed here. Hence the formula to find the M-th number will be: 

Mth number: (M-1)*9 + N

Below is the implementation of the above approach: 

C++
// C++ program to Find m-th number whose // sum of digits of a number until // sum becomes single digit is N #include <bits/stdc++.h> using namespace std;  // Function to find the M-th // number whosesum till one digit is N int findNumber(int n, int m) {     int num = (m - 1) * 9 + n;     return num; }  // Driver Code int main() {      int n = 2, m = 5;     cout << findNumber(n, m);     return 0; } 
Java
// Java program to Find m-th number whose // sum of digits of a number until // sum becomes single digit is N import java.io.*; public class GFG {  // Function to find the M-th // number whosesum till one digit is N static int findNumber(int n, int m) {     int num = (m - 1) * 9 + n;     return num; }  // Driver Code public static void main(String args[]) {     int n = 2, m = 5;     System.out.print(findNumber(n, m)); } }  // This code is contributed // by Akanksha Rai 
Python3
# Python3 program to Find m-th number  # whose sum of digits of a number # until sum becomes single digit is N   # Function to find the M-th  # number whosesum till one digit is N def findNumber(n, m) :          num = (m - 1) * 9 + n;      return num;   # Driver Code  if __name__ == "__main__" :       n = 2 ;     m = 5 ;      print(findNumber(n, m))      # This code is contributed by Ryuga 
C#
// C# program to Find m-th number whose // sum of digits of a number until // sum becomes single digit is N using System;  class GFG {  // Function to find the M-th // number whosesum till one digit is N static int findNumber(int n, int m) {     int num = (m - 1) * 9 + n;     return num; }  // Driver Code public static void Main() {     int n = 2, m = 5;     Console.Write(findNumber(n, m)); } }  // This code is contributed // by Akanksha Rai 
PHP
<?php // PHP program to Find m-th number whose // sum of digits of a number until // sum becomes single digit is N  // number whosesum till one digit is N function findNumber($n, $m) {     $num = ($m - 1) * 9 + $n;     return $num; }  // Driver Code $n = 2; $m = 5; echo findNumber($n, $m);  // This code is contributed // by Akanksha Rai ?> 
JavaScript
<script>  // JavaScript program to Find m-th number whose // sum of digits of a number until // sum becomes single digit is N          // Function to find the M-th     // number whosesum till one digit is N     function findNumber(n , m) {         var num = (m - 1) * 9 + n;         return num;     }      // Driver Code              var n = 2, m = 5;         document.write(findNumber(n, m));  // This code contributed by Rajput-Ji  </script> 

Output
38

Time Complexity: O(1), as we are doing constant time operations without using any loops or recursion.
Auxiliary Space: O(1), as we are not using any extra space.


Next Article
Find the smallest number whose digits multiply to a given number n

S

Striver
Improve
Article Tags :
  • Mathematical
  • Competitive Programming
  • DSA
  • number-digits
Practice Tags :
  • Mathematical

Similar Reads

  • Find the smallest number whose sum of digits is N
    Given a positive integers N, the task is to find the smallest number whose sum of digits is N.Example: Input: N = 10Output: 19Explanation: 1 + 9 = 10 = N Input: N = 18Output: 99Explanation: 9 + 9 = 18 = N Naive Approach: A Naive approach is to run a loop of i starting from 0 and find Sum of digits o
    6 min read
  • Find the smallest number whose digits multiply to a given number n
    Given a number 'n', find the smallest number 'p' such that if we multiply all digits of 'p', we get 'n'. The result 'p' should have minimum two digits.Examples: Input: n = 36 Output: p = 49 // Note that 4*9 = 36 and 49 is the smallest such number Input: n = 100 Output: p = 455 // Note that 4*5*5 = 1
    8 min read
  • Sum and Product of digits in a number that divide the number
    Given a positive integer N. The task is to find the sum and product of digits of the number which evenly divides the number n. Examples: Input: N = 12 Output: Sum = 3, product = 2 1 and 2 divide 12. So, their sum is 3 and product is 2. Input: N = 1012 Output: Sum = 4, product = 2 1, 1 and 2 divide 1
    5 min read
  • Find the Largest number with given number of digits and sum of digits
    Given an integer s and d, The task is to find the largest number with given digit sum s and the number of digits d. Examples: Input: s = 9, d = 2Output: 90 Input: s = 20, d = 3Output: 992 Recommended PracticeLargest number possibleTry It! Naive Approach: Consider all m digit numbers and keep a max v
    13 min read
  • Smallest positive number made up of non-repeating digits whose sum of digits is N
    Given a positive integer N, the task is to find the smallest positive number made up of distinct digits having sum of its digits equal to N. If no such number exists, print "-1". Examples: Input: N = 11Output: 29Explanation: The sum of the digits = 2 + 9 = 11 ( = N). Input: N = 46Output: -1 Approach
    6 min read
  • Represent a number as the sum of positive numbers ending with 9
    Given an integer N, the task is to check if N can be expressed as a sum of integers having 9 as the last digit (9, 19, 29, 39...), or not. If found to be true, then find the minimum count of such integers required to obtain N. Otherwise print -1. Examples: Input: N = 156Output: 4Explanation:156 = 9
    5 min read
  • Find the maximum sum of digits of the product of two numbers
    Given an array arr[] of size N( > 2). The task is to find the maximum sum of digits of the product of any two numbers of the given array.Examples: Input : arr[] = {8, 7} Output : 11 The product of 8 and 7 is 56. The sum of the digits of 56 is equal to 11.Input : arr[] = {4, 3, 5} Output : 6 Produ
    5 min read
  • n-th number whose sum of digits is ten
    Given an integer value n, find out the n-th positive integer whose sum is 10. Examples: Input: n = 2 Output: 28 The first number with sum of digits as 10 is 19. Second number is 28. Input: 15 Output: 154 Method 1 (Simple): We traverse through all numbers. For every number, we find the sum of digits.
    8 min read
  • Find second smallest number from sum of digits and number of digits
    Given the sum of digits as S and the number of digits as D, the task is to find the second smallest number Examples: Input: S = 9, D = 2Output: 27Explanation: 18 is the smallest number possible with sum = 9 and total digits = 2, Whereas the second smallest is 27. Input: S = 16, D = 3Output: 178Expla
    8 min read
  • Find the kth smallest number with sum of digits as m
    Given two integers M and K, the task is to find the Kth smallest number with digit sum as M.Examples: Input: M = 5, K = 3 Output: 23 Sequence of numbers starting from 1 with digit sum as 5 is as follows: 5 14 23 32 41 So 3rd smallest number is 23Input: M = 4, K = 1 Output: 4 Approach: We need to fin
    6 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