Skip to content
Related Articles

Related Articles

Print all the possible arithmetic expressions for a given number
  • Last Updated : 28 Apr, 2020

Given an integer N, the task is to print all the possible arithmetic expressions using all numbers from 1 to N and with binary operator +, –, * and /.

Examples:

Input: n = 2
Output:
1+2, 1-2, 1/2, 1*2

Input: n = 3
Output:
1+2+3, 1+2-3, 1+2/3, 1+2*3, 1-2+3, 1-2-3, 1-2/3, 1-2*3
1/2+3, 1/2-3, 1/2/3, 1/2*3, 1*2+3, 1*2-3, 1*2/3, 1*2*3

Approach:

  • We will create a character array of length = n + n – 1, because for an expression with n operands to be valid we will need n-1 operators.
  • Iterate the array and put numbers at even position whereas symbols at the odd position and call the function recursively.
  • If number of characters becomes equal to the length of array, print the array.

Below is the implementation of the above approach:




// C++ program to print all the 
// expressions for the input value 
  
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
  
// Function to print all the
// expressions using the number
void PrintRecursive(char *str,int arr[],
                 int i, int n,char *res,
                 int j, int len,int ln)
{
    // Termination condition
    if(j==len)
    {
        res[j]='\0';
        cout<<res<<endl;
        return;
    }
    // Even position will contain 
    // the numbers
    if(j%2==0)
    {
        res[j]='0'+arr[i];
          
        // Recursive call
         PrintRecursive(str,arr,i+1,n,res,
                        j+1,len,ln);
    }
    else
    {
        // Add a symbol from string in 
        // odd postion.
        for(int k=0;k<ln;k++)
        {
            res[j]=str[k];
            PrintRecursive(str,arr,i,n,res,
                           j+1,len,ln);
        }
    }
}
  
void PrintExpressions(int n)
{
    // Character array containing 
    // expressions 
    char str[4]={'+','-','/','*'};
     
    str[4]='\0';
      
    int ln=strlen(str);
      
    int a[n];
    for(int i=0;i<n;i++)
    {
        a[i] = i + 1;
    }
    char res[( 2 * n ) - 1];
      
    PrintRecursive(str,a,0,n,res,0,
                   2*n-1,ln);
    return;
}
  
//Driver code
int main()
{
    int n = 2;
      
    PrintExpressions(n);
       
    return 0;
}
Output:
1+2
1-2
1/2
1*2



My Personal Notes arrow_drop_up
Recommended Articles
Page :