给定整数N,任务是找到一个N位数,以使其不能被其任何位数整除。
注意:每个N值可以有多个答案。
例子:
Input: N = 4
Output: 6789
Explanation:
As the number 6789 is not divisible by any of its digits that is 6, 7, 8 and 9 and it is also a four digit number, Hence it can be the desired number.
Input: N = 2
Output: 57
Explanation:
As the number 57 is not divisible by any of its digits that is 5 and 7 and it is also a 2-digit number, Hence it can be the desired number.
方法:问题中的主要观察结果是2和3是不相除的数字,数字“ 23、233、2333,…”也不能被2或3整除。因此,对于任何N-位数,最高有效位数为2,其余位数为3以获取所需的数字。
算法:
- 检查N的值是否等于1,则不可能有这样的数字,因此返回-1。
- 否则,初始化变量num ,将数字存储为2。
- 运行一个从1到N的循环,然后对于每次迭代将该数字乘以10并加3。
num = (num * 10) + 3
下面是上述方法的实现:
C++
// C++ implementation to find a
// N-digit number such that the number
// it is not divisible by its digits
#include
using namespace std;
typedef long long int ll;
// Function to find the number
// such that it is not divisible
// by its digits
void solve(ll n)
{
// Base Cases
if (n == 1)
{
cout << -1;
}
else {
// First Digit of the
// number will be 2
int num = 2;
// Next digits of the numbers
for (ll i = 0; i < n - 1; i++) {
num = (num * 10) + 3;
}
cout << num;
}
}
// Driver Code
int main()
{
ll n = 4;
// Function Call
solve(n);
}
Java
// Java implementation to find a
// N-digit number such that the number
// it is not divisible by its digits
class GFG {
long ll;
// Function to find the number
// such that it is not divisible
// by its digits
static void solve(long n)
{
// Base Cases
if (n == 1)
{
System.out.println(-1);
}
else {
// First Digit of the
// number will be 2
int num = 2;
// Next digits of the numbers
for (long i = 0; i < n - 1; i++) {
num = (num * 10) + 3;
}
System.out.println(num);
}
}
// Driver Code
public static void main (String[] args)
{
long n = 4;
// Function Call
solve(n);
}
}
// This code is contributed by AnkitRai01
Python3
# Python3 implementation to find a
# N-digit number such that the number
# it is not divisible by its digits
# Function to find the number
# such that it is not divisible
# by its digits
def solve(n) :
# Base Cases
if (n == 1) :
print(-1);
else :
# First Digit of the
# number will be 2
num = 2;
# Next digits of the numbers
for i in range(n - 1) :
num = (num * 10) + 3;
print(num);
# Driver Code
if __name__ == "__main__" :
n = 4;
# Function Call
solve(n);
# This code is contributed by AnkitRai01
C#
// C# implementation to find a
// N-digit number such that the number
// it is not divisible by its digits
using System;
class GFG {
long ll;
// Function to find the number
// such that it is not divisible
// by its digits
static void solve(long n)
{
// Base Cases
if (n == 1)
{
Console.WriteLine(-1);
}
else {
// First Digit of the
// number will be 2
int num = 2;
// Next digits of the numbers
for (long i = 0; i < n - 1; i++) {
num = (num * 10) + 3;
}
Console.WriteLine(num);
}
}
// Driver Code
public static void Main(String[] args)
{
long n = 4;
// Function Call
solve(n);
}
}
// This code is contributed by sapnasingh4991
输出:
2333
性能分析:
- 时间复杂度: O(N)。
- 辅助空间: O(1)。