Find the first N integers such that the sum of their digits is equal to 10
Given an integer N, the task is to print first N integers whose sum of digits is 10.
Examples:
Input: N = 4
Output: 19 28 37 46
Input: N = 6
Output: 19 28 37 46 55 64
Approach: Initialise num = 19 to get the first number of the series, now add 9 to the previous number and check whether the sum of the digits of the new number is 10. If yes then this is the next number of the series, this is because the difference between any two consecutive numbers of the required series is at least 9.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sum( int n)
{
int sum = 0;
while (n) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
void firstN( int n)
{
int num = 19, cnt = 1;
while (cnt != n) {
if (sum(num) == 10) {
cout << num << " " ;
cnt++;
}
num += 9;
}
}
int main()
{
int n = 10;
firstN(n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int sum( int n)
{
int sum = 0 ;
while (n > 0 )
{
sum = sum + n % 10 ;
n = n / 10 ;
}
return sum;
}
static void firstN( int n)
{
int num = 19 , cnt = 1 ;
while (cnt != n)
{
if (sum(num) == 10 )
{
System.out.print(num + " " );
cnt++;
}
num += 9 ;
}
}
public static void main(String[] args)
{
int n = 10 ;
firstN(n);
}
}
|
Python3
def sum (n) :
sum = 0 ;
while (n) :
sum = sum + n % 10 ;
n = n / / 10 ;
return sum ;
def firstN(n) :
num = 19 ; cnt = 1 ;
while (cnt ! = n) :
if ( sum (num) = = 10 ) :
print (num,end = " " );
cnt + = 1 ;
num + = 9 ;
if __name__ = = "__main__" :
n = 10 ;
firstN(n);
|
C#
using System;
class GFG
{
static int sum( int n)
{
int sum = 0;
while (n > 0)
{
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
static void firstN( int n)
{
int num = 19, cnt = 1;
while (cnt != n)
{
if (sum(num) == 10)
{
Console.Write(num + " " );
cnt++;
}
num += 9;
}
}
public static void Main(String[] args)
{
int n = 10;
firstN(n);
}
}
|
Javascript
<script>
function sum(n) {
var sum = 0;
while (n > 0) {
sum = sum + n % 10;
n = parseInt(n / 10);
}
return sum;
}
function firstN(n) {
var num = 19, cnt = 1;
while (cnt != n) {
if (sum(num) == 10) {
document.write(num + " " );
cnt++;
}
num += 9;
}
}
var n = 10;
firstN(n);
</script>
|
Output:
19 28 37 46 55 64 73 82 91
Time Complexity: O(n*log(n))
Auxiliary Space: O(1)
Last Updated :
29 Mar, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...