Home > Back-end >  How to solve this Function problem with Java?
How to solve this Function problem with Java?

Time:08-01

enter image description hereGiven an integer N, find all possible pairs of A, and B such that A B = N and A and B both are natural numbers ??

My Code:-

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);
    }
}

CodePudding user response:

The basic algorithm to solve this problem:

Used two for loop for "a" and "b" to find the pairs where 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)));
    }
}

OR

You may only one for loop for "a", and the "N - a" will be the value of "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;
}

CodePudding user response:

You can use For Loop for this task. First create two nested loops from 1 to N, and if check for what you need. If you need I'll show you example :)

  • Related