用有 Z 位的 GCD 分别求 X 位和 Y 位的两个数 A 和 B
给定三个正整数X 、 Y和Z 。任务是找到两个分别为X和Y位的数字A和B ,它们的 GCD 有Z位。其中Z ≤ min(X, Y) 。如果有多个可能的答案,请打印其中任何一个。
例子:
Input: X = 2, Y = 3, Z = 1
Output: A = 11, B = 100
Explanation: A and B contains 2 and 3 digits respectively and GCD(A, B) is 1 which has 1 digit.
Input: X = 2, Y = 2, Z = 2
Output: A = 13, B = 26
方法:可以使用一些观察来解决该任务。计算A等于10 x-1 , B等于10 y-1 , C等于10 z-1 。用C增加A以实现Z位的 GCD。请按照以下步骤解决问题:
- 用 1 初始化 3 个变量 A、B、C。
- 用 C 附加 Z -1 个零。
- 在 A 的最后一个附加 X – 1 个零。
- 在 B 的最后一个附加 Y - 1 个零。
- 将 A 增加 C 的值。
- 打印 A 和 B 作为答案。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the desired numbers
void findTwoNumbers(int X, int Y, int Z)
{
int A, B, C;
A = B = C = 1;
for (int i = 1; i <= X - 1; i++) {
A = A * 10;
}
for (int i = 1; i <= Y - 1; i++) {
B = B * 10;
}
for (int i = 1; i <= Z - 1; i++) {
C = C * 10;
}
A = A + C;
cout << "A = " << A << " B = " << B;
}
// Driver Code
int main()
{
int X = 2, Y = 3, Z = 1;
findTwoNumbers(X, Y, Z);
return 0;
}
Java
// Java program for the above approach
class GFG {
// Function to find the desired numbers
static void findTwoNumbers(int X, int Y, int Z) {
int A, B, C;
A = B = C = 1;
for (int i = 1; i <= X - 1; i++) {
A = A * 10;
}
for (int i = 1; i <= Y - 1; i++) {
B = B * 10;
}
for (int i = 1; i <= Z - 1; i++) {
C = C * 10;
}
A = A + C;
System.out.println("A = " + A + " B = " + B);
}
// Driver Code
public static void main(String args[]) {
int X = 2, Y = 3, Z = 1;
findTwoNumbers(X, Y, Z);
}
}
// This code is contributed by Saurabh Jaiswal
Python3
# python3 program for the above approach
# Function to find the desired numbers
def findTwoNumbers(X, Y, Z):
A = B = C = 1
for i in range(1, X):
A = A * 10
for i in range(1, Y):
B = B * 10
for i in range(1, Z):
C = C * 10
A = A + C
print(f"A = {A} B = {B}")
# Driver Code
if __name__ == "__main__":
X, Y, Z = 2, 3, 1
findTwoNumbers(X, Y, Z)
# This code is contributed by rakeshsahni
C#
// C# program for the above approach
using System;
public class GFG
{
// Function to find the desired numbers
static void findTwoNumbers(int X, int Y, int Z)
{
int A, B, C;
A = B = C = 1;
for (int i = 1; i <= X - 1; i++) {
A = A * 10;
}
for (int i = 1; i <= Y - 1; i++) {
B = B * 10;
}
for (int i = 1; i <= Z - 1; i++) {
C = C * 10;
}
A = A + C;
Console.Write("A = " + A + " B = " + B);
}
// Driver Code
public static void Main()
{
int X = 2, Y = 3, Z = 1;
findTwoNumbers(X, Y, Z);
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
A = 11 B = 100
时间复杂度:O(max(X, Y))
辅助空间:O(1)