Smallest number whose sum of digits is square of N
Given an integer N, the task is to find the smallest number whose sum of digits is N2.
Examples:
Input: N = 4
Output: 79
24 = 16
sum of digits of 79 = 76
Input: N = 6
Output: 9999
210 = 1024 which has 4 digits
Approach: The idea is to find the general term for the smallest number whose sum of digits is square of N. That is
// First Few terms
First Term = 1 // N = 1
Second Term = 4 // N = 2
Third Term = 9 // N = 3
Fourth Term = 79 // N = 4
.
.
Nth Term:
*** QuickLaTeX cannot compile formula:
*** Error message:
Error: Nothing to show, formula is empty
<sup>(n^2 \% 9 + 1) * 10 ^ {\lfloor n^2/9 \rfloor} - 1 </sup>
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int smallestNum( int n)
{
return (n * n % 9 + 1) * pow (10, n * n / 9) - 1;
}
int main()
{
int n = 4;
cout << smallestNum(n);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int smallestNum( int n)
{
return ( int )((n * n % 9 + 1 ) *
Math.pow( 10 , n * n / 9 ) - 1 );
}
public static void main(String[] args)
{
int n = 4 ;
System.out.print(smallestNum(n));
}
}
|
Python 3
def smallestNum(n):
return ((n * n % 9 + 1 ) *
pow ( 10 , int (n * n / 9 )) - 1 )
N = 4
print (smallestNum(N))
|
C#
using System;
class GFG{
static int smallestNum( int n)
{
return ( int )((n * n % 9 + 1) *
Math.Pow(10, n * n / 9) - 1);
}
public static void Main(String[] args)
{
int n = 4;
Console.Write(smallestNum(n));
}
}
|
Javascript
<script>
function smallestNum( n) {
return parseInt (n * n % 9 + 1) * Math.pow(10, parseInt(n*n / 9)) -1;
}
let n = 4;
document.write(smallestNum(n));
</script>
|
Time complexity: O(log10n2) for given n, as pow function is being used
Auxiliary space: O(1)
Last Updated :
22 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...