Z Three Numbers
Question
Z Three Numbers
Given two numbers K and S Determine how many different values of X,Y and Z such that (0≤ X,Y,Z≤ K) and X=Y+Z=S.
Input
Only none line containing two numbers K and S(0≤ K ≤3000, 0≤ S ≤3K)
Output
Print the answer required below
Examples
Input |
2 1 |
Output |
3 |
Note
In the first test call all values of X,Y,Z that satisfy the condition are:
001
010
100
In the second test case all values of X,Y,Z that actually the conditions are:
XYZ | XYZ | XYZ | XYZ |
004 | 040 | 202 | 310 |
013 | 103 | 211 | 400 |
022 | 112 | 220 | 130 |
031 | 121 | 301 |
Summary
Initially, we will take two input from user in the form of number named ‘k’ and ‘s’. So later we will find the combination of the x,y,z, so that it will be equal to ‘s’ such a that x+y+z=s. Also have to noticed that the x,y, and z should be between 0 to ‘k’ in the combination.
Explanation
Basically count is set to 0. So Input function are used to take the input from the user, in the form of ‘k’ and ‘s’ values. Later we have created a function comb to which as an argument we have passed array, size of the array, combination size and s. After that from the comb function we will call the another function named util where we have passed seven arguments. Such that in this util function the recursion process will be executed where it will find the combination of three number i.e. x,y, and z.
Each time when the process happens we will check the sum of that three numbers. If the sum of that three number is equal to s or not, If yes, then we will check if entered two element are same, after permutation will be 3. And will get added to our count. If entered three number are different from one another then the permutation will be 6. And it will get added to count. Finally the count value will get printed on the screen as output.
Code
#include <iostream> using namespace std; int count=0; void util(int arr[], int d[],int start,int end,int index,int r,int s) { if (index == r) { int sum=0; /* to find the sum of elements in the combination */ for (int j = 0; j < r; j++) sum+=d[j]; /* if the sum mateches with the 's' value */ if(sum==s) { if(r==1) count+=3; /* if the combination size is 2 */ else if(r==2){ /* if one of the two elements are same */ if(d[0]==d[1] || d[0]==0 || d[1]==0) count+=3; /* if all are different */ else count+=6; } /* if the size of combination is 3 */ else if(r==3) count+=6; } return; } for (int i=start; i<=end && (end-i+1)>=(r-index); i++) { d[index]=arr[i]; util(arr,d, i+1,end, index+1, r,s); } } void comb(int arr[],int n,int r,int s) { /* array to store each combination at a time */ int d[r]; /* to get the combinations using using recursion in util function */ util(arr, d, 0, n-1, 0, r,s); } /* driver code */ int main() { int k,s; cin>>k>>s; int arr[k+1]; for(int i=0;i<=k;i++) arr[i]=i; comb(arr,k+1,2,s); comb(arr,k+1,3,s); cout<<count<<endl; }
Output
Also read, make a story like a worker or game of using inheritance.