
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if We Can Buy Product with Given Money in C++
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
Advertisements