给定数字N ,任务是找到平方数为N位数的最小数字。
例子:
Input: N = 2
Output: 4
Explanation:
32 = 9, which has 1 digit.
42 = 16, which has 2 digits.
Hence, 4 is the smallest number whose square has N digits.
Input: N = 3
Output: 10
Explanation:
102 = 100, which has 3 digits.
天真的方法:解决问题的最简单方法是从每个数字的平方开始计算,并计算其平方中的位数。打印第一个数字,该数字的平方是N位数字。
时间复杂度: O(√(10 N ))
有效方法:要解决此问题,我们需要进行以下观察:
The smallest number whose square has 1 digit = 1
The smallest number whose square has 2 digits = 4
The smallest number whose square has 3 digits = 10
The smallest number whose square has 4 digits = 32
The smallest number whose square has 5 digits = 100
Hence, these numbers form a series 1, 4, 10, 32, 100, 317, …….
现在,我们需要找到该系列的第N个项的公式。
该系列的术语可以用以下形式表示:
If N = 1, Smallest number possible is 1.
If N = 2, Smallest number possible is 41.
If N = 3, Smallest number possible is 10.
因此,我们可以得出结论:该系列的第N个可以表示为
因此,为了解决该问题,我们只需要为给定的整数N计算ceil(10 (N – 1)/ 2 ) 。
下面是上述方法的实现:
C++
// C++ Program to find the smallest
// number whose square has N digits
#include
using namespace std;
// Function to return smallest number
// whose square has N digits
int smallestNum(int N)
{
// Calculate N-th term of the series
float x = pow(10.0, (N - 1) / 2.0);
return ceil(x);
}
// Driver Code
int main()
{
int N = 4;
cout << smallestNum(N);
return 0;
}
Java
// Java program for above approach
class GFG{
// Function to return smallest number
// whose square has N digits
static int smallestNum(int N)
{
// Calculate N-th term of the series
float x = (float)(Math.pow(10, (N - 1) / 2.0));
return (int)(Math.ceil(x));
}
// Driver code
public static void main(String[] args)
{
int N = 4;
System.out.print(smallestNum(N));
}
}
// This code is contributed by spp
Python3
# Python3 Program to find the smallest
# number whose square has N digits
import math;
# Function to return smallest number
# whose square has N digits
def smallestNum(N):
# Calculate N-th term of the series
x = pow(10.0, (N - 1) / 2.0);
return math.ceil(x);
# Driver Code
N = 4;
print(smallestNum(N));
# This code is contributed by Code_mech
C#
// C# program for above approach
using System;
class GFG{
// Function to return smallest number
// whose square has N digits
static int smallestNum(int N)
{
// Calculate N-th term of the series
float x = (float)(Math.Pow(10, (N - 1) / 2.0));
return (int)(Math.Ceiling(x));
}
// Driver code
public static void Main()
{
int N = 4;
Console.Write(smallestNum(N));
}
}
// This code is contributed by Code_Mech
32
时间复杂度: O(log(N))
辅助空间: O(1)