[英]How to solve this Function problem with Java?
在此处输入图像描述给定 integer N,找到所有可能的 A 和 B 对,使得 A + B = N 和 A 和 B 都是自然数?
我的代码:-
import java.io.*;
import java.util.*;
class UserMainCode
{
public int AllPair(int input1){
Int count0;
int N = Input1;
if(N == A + B) {
System.out.println(Allpair);
}
}
解决这个问题的基本算法:
对“ a ”和“ b ”使用两个 for 循环来查找a + b == N的对
public static Map<Integer,Integer> getPossibleSum(Integer n){
Map<Integer,Integer> pair = new HashMap<>();
for(int a = 0; a < n; a++){
for(int b = 0; b <n; b++){
if(a + b == n){
pair.put(a,b);
}
}
}
return pair;
}
public static void main(String[] args) {
Map<Integer,Integer> pair = getPossibleSum(10);
for (Integer key : pair.keySet()) {
System.out.println(String.format("[a: %d; b: %d]", key, pair.get(key)));
}
}
或者
“ a ”可能只有一个 for 循环,“ N - a ”将是“ b ”的值
public static Map<Integer,Integer> getPossibleSum(Integer n){
Map<Integer,Integer> pair = new HashMap<>();
for(int a = 1; a < n; a++){
pair.put(a,n-a);
}
return pair;
}
您可以使用For Loop
来完成此任务。 首先创建两个从 1 到 N 的nested loops
,并if check
您需要的内容。 如果您需要,我会向您展示示例:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.