将给定数字拆分为两个具有 GCD 1 的不同数字
给定一个整数作为N ,任务是将N转换为两个数字a和b ,使得a < b并且GCD(a, b)等于 1。
例子:
Input: N = 12
Output: 5 7
Input: N = 9
Output: 4 5
方法:这个想法是从数字本身开始从循环的后面开始迭代。请按照以下步骤解决问题。
- 如果N小于等于2,则答案不存在。
- 否则,使用变量i遍历范围[N/2, 0)并执行以下任务:
- 如果i和Ni的 gcd 为1 ,则将其打印为答案并返回。
下面是上述方法的实现:
C++
/// C++ program for the above approach
#include
using namespace std;
// Function to split N into two numbers
void find(int n)
{
// Base Case
if (n <= 2) {
cout << "-1";
}
else {
// Since a < b
// start from n/2
for (int i = n / 2; i > 0; i--) {
// Sum of a and b is n
int a = i, b = n - i;
// Check the gcd
if (__gcd(a, b) == 1 && a < b) {
cout << a <<", " << b;
return;
}
}
}
}
// Driver Code
int main()
{
int N = 9;
find(N);
return 0;
}
Java
/// Java program for the above approach
class GFG {
// Function to split N into two numbers
public static void find(int n) {
// Base Case
if (n <= 2) {
System.out.println("-1");
} else {
// Since a < b
// start from n/2
for (int i = n / 2; i > 0; i--) {
// Sum of a and b is n
int a = i, b = n - i;
// Check the gcd
if (__gcd(a, b) == 1 && a < b) {
System.out.println(a + ", " + b);
return;
}
}
}
}
static int __gcd(int a, int b) {
if (b == 0)
return a;
return __gcd(b, a % b);
}
// Driver Code
public static void main(String args[]) {
int N = 9;
find(N);
}
}
// This code is contributed by saurabh_jaiswal.
Python3
# Python 3 program for the above approach
import math
# Function to split N into two numbers
def find(n):
# Base Case
if (n <= 2):
print("-1")
else:
# Since a < b
# start from n/2
for i in range(n // 2, -1, -1):
# Sum of a and b is n
a = i
b = n - i
# Check the gcd
if (math.gcd(a, b) == 1 and a < b):
print(a,",", b)
return
# Driver Code
if __name__ == "__main__":
N = 9
find(N)
#vThis code is contributed by ukasp.
C#
/// C# program for the above approach
using System;
public class GFG {
// Function to split N into two numbers
public static void find(int n) {
// Base Case
if (n <= 2) {
Console.WriteLine("-1");
} else {
// Since a < b
// start from n/2
for (int i = n / 2; i > 0; i--) {
// Sum of a and b is n
int a = i, b = n - i;
// Check the gcd
if (__gcd(a, b) == 1 && a < b) {
Console.WriteLine(a + ", " + b);
return;
}
}
}
}
static int __gcd(int a, int b) {
if (b == 0)
return a;
return __gcd(b, a % b);
}
// Driver Code
public static void Main(String []args) {
int N = 9;
find(N);
}
}
// This code is contributed by 29AjayKumar
Javascript
输出
4, 5
时间复杂度: O(N log(N))
辅助空间: O(1)