C++ program to check we can buy product with given money or not



Suppose we have a number N. A cake seller is selling cakes with 40 rupees, and doughnuts with 70 rupees each. We have to check whether we can buy some of them with exactly N rupees or not.

So, if the input is like N = 110, then the output will be True, because 40 + 70 = 110.

To solve this, we will follow these steps −

o := false Define a function dfs(), this will take i, if i > n, then:    return false if i is same as n, then:    return true if dfs(i + 40), then:    return true return dfs(i + 70) From the main method, do the following n := N o := dfs(0) return o

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; int n; bool o = false; bool dfs(int i) { if (i > n) return false; if (i == n) return true; if (dfs(i + 40)) return true; return dfs(i + 70); } bool solve(int N) { n = N; o = dfs(0); return o; } int main(){ int N = 110; cout << solve(N) << endl; }

Input

110 

Output

1
Updated on: 2022-02-25T13:02:27+05:30

240 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements