# Java Program : Get all possible values of X such that A % X = B

Question:  Write a java program to get  all possible values of X such that A % X = B. Input two integers A and B. The task is to find the  all possible values X such that A % X = B. If there are infinite number of possible values then print -1.

Examples:

1. Input: A = 21, B = 5
Output: 2
8 and 16 are the only valid values for X.
2. Input: A = 5, B = 5
Output: -1
X can have any value > 5

# Algorithm

• Step 1: Ask the user to input values of A and B
• Step 2: Find out all possible factors of (A-B) which are greater than B
• Step 3: Use StringJoiner to print the possible value in comma separated form.

# Java Program

```public class Program1 {
public static void main(String[] args) {
System.out.println("Enter values of A and B to get possible values of X from expression A % X = B");

Scanner input = new Scanner(System.in);
System.out.print("Please Enter an integer A: ");
int A = input.nextInt();

System.out.print("Please Enter an integer B: ");
int B = input.nextInt();

System.out.println("Possible Values of X :" + getAllowedValues(A, B));
}

private static String getAllowedValues(int A, int B) {
//Use to print value in comma separated form
StringJoiner joiner = new StringJoiner(",");

if (A - B > 0) {
//find out all possible factor of(A-B) which are greater than B
for (int C = (A - B); C > 0 & C > B; C /= 2) {
if ((A - B) % C == 0)
}
} else {
}
return joiner.toString();
}

}
```

## Output

``````
Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 21
Please Enter an integer B: 5
Possible Values of X :16,8

Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 5
Please Enter an integer B: 5
Possible Values of X :-1

``````