找到一个三元组 (X, Y, Z) 使得所有元素都可以被 A 整除,恰好一个可以被 A 和 B 整除,并且 X + Y = Z
给定两个整数A和B ,任务是找到一个三元组(X, Y, Z)使得它们都可以被A整除,其中恰好一个可以被A和B整除,并且X + Y = Z。
例子:
Input: A = 5, B = 3
Output: 10 50 60
Explanation: For the triplet (10, 50, 60), all of them are divisible by 5, 60 is divisible by both 5 and 3, and 10 + 50 = 60. Therefore, (10, 50, 60) is valid triplet. Other possible triplets are (5, 25, 30), (5, 15, 20)
Input: A = 7, B = 11
Output: 28 154 182
方法:给定的问题是一个基于观察的问题,可以使用基础数学来解决。可以观察到,三元组(A, A * B, A * (B + 1))满足所有给定条件,但B的值为1时除外。在这种情况下,可以看出,它们中的一个恰好可以被A和B整除的条件总是会被违反。因此,如果B = 1 ,则不存在有效的三元组,否则打印(A, A * B, A * (B + 1)) 。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
// Function to find a triplet (X, Y, Z)
// such that all of them are divisible
// by A, exactly one of them is divisible
// by both A and B, and X + Y = Z
void findTriplet(int A, int B)
{
// If the value of B is 1
if (B == 1) {
cout << -1;
return;
}
// Print Answer
cout << A << " " << A * B
<< " " << A * (B + 1);
}
// Driver Code
int main()
{
int A = 5;
int B = 3;
findTriplet(A, B);
return 0;
}
Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
// Function to find a triplet (X, Y, Z)
// such that all of them are divisible
// by A, exactly one of them is divisible
// by both A and B, and X + Y = Z
static void findTriplet(int A, int B)
{
// If the value of B is 1
if (B == 1) {
System.out.println(-1);
return;
}
// Print Answer
System.out.println(A + " " + A * B + " " + A * (B + 1));
}
// Driver Code
public static void main (String[] args) {
int A = 5;
int B = 3;
findTriplet(A, B);
}
}
// This code is contributed by hrithikgarg03188.
Python3
# Python code for the above approach
# Function to find a triplet (X, Y, Z)
# such that all of them are divisible
# by A, exactly one of them is divisible
# by both A and B, and X + Y = Z
def findTriplet(A, B):
# If the value of B is 1
if (B == 1):
print(-1)
return
# Print Answer
print(f"{A} {A * B} {A * (B + 1)}")
# Driver Code
A = 5
B = 3
findTriplet(A, B)
# This code is contributed by Saurabh Jaiswal
C#
// C# program of the above approach
using System;
class GFG
{
// Function to find a triplet (X, Y, Z)
// such that all of them are divisible
// by A, exactly one of them is divisible
// by both A and B, and X + Y = Z
static void findTriplet(int A, int B)
{
// If the value of B is 1
if (B == 1) {
Console.Write(-1);
return;
}
// Print Answer
Console.Write(A + " " + A * B + " " + A * (B + 1));
}
// Driver Code
public static int Main()
{
int A = 5;
int B = 3;
findTriplet(A, B);
return 0;
}
}
// This code is contributed by Taranpreet
Javascript
输出
5 15 20
时间复杂度: O(1)
辅助空间: O(1)