Dado un número entero N , la tarea es encontrar el número más pequeño cuya suma de dígitos sea N 2 .
Ejemplos:
Entrada: N = 4
Salida: 79
2 4 = 16
suma de dígitos de 79 = 76
Entrada: N = 6
Salida: 9999
2 10 = 1024 que tiene 4 dígitos
Enfoque : La idea es encontrar el término general para el número más pequeño cuya suma de dígitos es el cuadrado de N. Eso es
// 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>
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the above approach #include <bits/stdc++.h> using namespace std; // Function to return smallest // number whose sum of digits is n^2 int smallestNum(int n) { cout<<pow(10, n * n / 9)<<endl; return (n * n % 9 + 1) * pow(10, n * n / 9) - 1; } // Driver Code int main() { int n = 4; cout << smallestNum(n); return 0; }
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
<script> // Javascript implementation of the above approach // Function to return smallest // number whose sum of digits is n^2 function smallestNum( n) { return parseInt (n * n % 9 + 1) * Math.pow(10, parseInt(n*n / 9)) -1; } // Driver Code let n = 4; document.write(smallestNum(n)); // This code contributed by aashish1995 </script>
Producción:
79