Print all numbers that can be obtained by adding A or B to N exactly M times | Java program for the above approach ; Function to find all possible numbers that can be obtained by adding A or B to N exactly N times ; If number of steps is 0 and only possible number is N ; Add A to N and make a recursive call for M - 1 steps ; Add B to N and make a recursive call for M - 1 steps . ; Driver Code ; Given Inputs ; Stores all possible numbers ; Function call ; Print all possible numbers
import java . util . * ; public class MyClass { static void possibleNumbers ( Set < Integer > numbers , int N , int M , int A , int B ) { if ( M == 0 ) { numbers . add ( N ) ; return ; } possibleNumbers ( numbers , N + A , M - 1 , A , B ) ; possibleNumbers ( numbers , N + B , M - 1 , A , B ) ; } public static void main ( String args [ ] ) { int N = 5 , M = 3 , A = 4 , B = 6 ; Set < Integer > numbers = new HashSet < Integer > ( ) ; possibleNumbers ( numbers , N , M , A , B ) ; Iterator < Integer > i = numbers . iterator ( ) ; while ( i . hasNext ( ) ) System . out . print ( i . next ( ) + " ▁ " ) ; } }