使用java和python实现 任意大于0小于1的分数n/m完成n/m=1/a+1/b
时间: 2023-12-30 07:06:40 浏览: 129
Java代码实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入分数n/m中的n和m:");
int n = scanner.nextInt();
int m = scanner.nextInt();
for (int a = 1; a <= n; a++) {
for (int b = 1; b <= m; b++) {
if ((n * b + m * a) == m * n) {
System.out.printf("%d/%d = 1/%d + 1/%d%n", n, m, b, a);
}
}
}
}
}
```
Python代码实现:
```python
n, m = map(int, input("请输入分数n/m中的n和m:").split())
for a in range(1, n+1):
for b in range(1, m+1):
if (n*b + m*a) == m*n:
print(f"{n}/{m} = 1/{b} + 1/{a}")
```
两者的思路类似,都是通过枚举a和b来寻找符合条件的解。对于每一组a和b,判断是否满足1/a + 1/b = n/m。如果满足,则输出对应的结果。
阅读全文