Print all numbers that can be obtained by adding A or B to N exactly M times | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void possibleNumbers ( set < int > & numbers , int N , int M , int A , int B ) { if ( M == 0 ) { numbers . insert ( N ) ; return ; } possibleNumbers ( numbers , N + A , M - 1 , A , B ) ; possibleNumbers ( numbers , N + B , M - 1 , A , B ) ; } int main ( ) { int N = 5 , M = 3 , A = 4 , B = 6 ; set < int > numbers ; possibleNumbers ( numbers , N , M , A , B ) ; for ( int x : numbers ) { cout << x << " ▁ " ; } return 0 ; }