- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find multiple of x closest to or a ^ b (a raised to power b) in C++
Suppose we have three values, a, b and x. We have to find one multiple of x, that is nearest to ab. Suppose the numbers are x = 4, a = 3, b = 3, then the output will be 28, as this is nearest to 33 = 27
The approach is simple; we have to follow these conditions −
If b < 0, and a = 1, then ab turns out to be 1 and hence, the closest multiple of x becomes either 0 or x.
If b < 0 and a > 1, then, ab, turns out to be less than 1, and hence the closest multiple of x becomes 0.
If b > 0, then find ab. Then let mul = integer of ab / x, then a closest multiple of x is mul*x or (mul + 1)*x
Example
#include<iostream> #include<cmath> using namespace std; void findMultiple(int a, int b, int x) { cout << "Nearest multiple: "; if (b < 0) { if (a == 1 && x == 1) cout << "1"; else cout << "0"; } int mul = pow(a, b); int ans = mul / x; int ans1 = x * ans; int ans2 = x * (ans + 1); if((mul - ans1) <= (ans2 - mul)){ cout << ans1; } else{ cout << ans2; } } int main() { int a = 3, b = 3, x = 4; findMultiple(a, b, x); }
Output
Nearest multiple: 28
Advertisements