给定一个整数N,任务是找到所有可能的黄金数字最小的n个位数整除,即,2,3,5和7。如果没有这样的数字,则打印-1 。
例子:
Input: N = 5
Output: 10080
Explanation: 10080 is the smallest five-digit number that is divisible by 2, 3, 5 and 7.
Input: N = 3
Output: 210
方法:
请按照以下步骤解决问题:
- 由于所有两个数字2、3、5、7都是素数,这意味着N也可以被其乘积2×3×5×7 = 210整除。
- 对于N <3 ,不存在这样的数字。因此,打印-1 。
- 对于N = 3 ,答案为210 。
- 对于N> 3 ,需要进行以下计算:
- 求出余数R = 10 N-1 %N 。
- 将210 – R加到10 N-1上。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to find the minimum number of
// n digits divisible by all prime digits
void minNum(int n)
{
if (n < 3)
cout << -1;
else
cout << (210 * ((int)(pow(10, n - 1) /
210) + 1));
}
// Driver Code
int main()
{
int n = 5;
minNum(n);
return 0;
}
// This code is contributed by amal kumar choubey
Java
// Java implementation of the above approach
class GFG{
// Function to find the minimum number of
// n digits divisible by all prime digits
static void minNum(int n)
{
if(n < 3)
System.out.println(-1);
else
System.out.println(210 * (
(int)(Math.pow(10, n - 1) / 210) + 1));
}
// Driver code
public static void main(String[] args)
{
int n = 5;
minNum(n);
}
}
// This code is contributed by Stuti Pathak
Python3
# Python3 implementation of the above approach
from math import *
# Function to find the minimum number of
# n digits divisible by all prime digits.
def minNum(n):
if n < 3:
print(-1)
else:
print(210 * (10**(n-1) // 210 + 1))
# Driver Code
n = 5
minNum(n)
C#
// C# implementation of the above approach
using System;
class GFG{
// Function to find the minimum number of
// n digits divisible by all prime digits
static void minNum(int n)
{
if (n < 3)
Console.WriteLine(-1);
else
Console.WriteLine(210 *
((int)(Math.Pow(10, n - 1) / 210) + 1));
}
// Driver code
public static void Main(String[] args)
{
int n = 5;
minNum(n);
}
}
// This code is contributed by amal kumar choubey
输出:
10080
时间复杂度: O(logN)
辅助空间: O(1)