给定整数N ,任务是找到位数之和为N 2的最小数字。
例子:
Input: N = 4
Output: 79
24 = 16
sum of digits of 79 = 76
Input: N = 6
Output: 9999
210 = 1024 which has 4 digits
方法:想法是找到位数为N的平方的最小数字的通用术语。
// 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
(n^2 \% 9 + 1) * 10 ^ {\lfloor n^2/9 \rfloor} - 1
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to return smallest
// number whose sum of digits is n^2
int smallestNum(int n)
{
cout<
Java
// Java implementation of the above approach
import java.util.*;
class GFG{
// Function to return smallest
// number whose sum of digits is n^2
static int smallestNum(int n)
{
return (int)((n * n % 9 + 1) *
Math.pow(10, n * n / 9) - 1);
}
// Driver Code
public static void main(String[] args)
{
int n = 4;
System.out.print(smallestNum(n));
}
}
// This code is contributed by Rajput-Ji
Python 3
# Python implementation of the above approach
# Function to return smallest
# number whose sum of digits is n^2
def smallestNum(n):
return ((n * n % 9 + 1) *
pow(10, int(n * n / 9)) - 1)
# Driver Code
# Given N
N = 4
print(smallestNum(N))
# This code is contributed by Vishal Maurya.
C#
// C# implementation of the above approach
using System;
class GFG{
// Function to return smallest
// number whose sum of digits is n^2
static int smallestNum(int n)
{
return (int)((n * n % 9 + 1) *
Math.Pow(10, n * n / 9) - 1);
}
// Driver Code
public static void Main(String[] args)
{
int n = 4;
Console.Write(smallestNum(n));
}
}
// This code is contributed by Rajput-Ji
Javascript
输出:
79