- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Find the multiple of x which is closest to a^b in C++
- K-th digit in ‘a’ raised to power ‘b’ in C++
- Find value of y mod (2 raised to power x) in C++
- Check if a number can be expressed as x^y (x raised to power y) in C++
- Find last five digits of a given five digit number raised to power five in C++
- Find the value of $(x-a)^3 + (x-b)^3 + (x-c)^3 - 3 (x-a)(x-b)(x-c)$ if $a+b+c = 3x$
- Bash program to find A to the power B?
- Number of digits in 2 raised to power n in C++
- Simplify:( left(frac{x^{a+b}}{x^{c}}right)^{a-b}left(frac{x^{b+c}}{x^{a}}right)^{b-c}left(frac{x^{c+a}}{x^{b}}right)^{c-a} )
- Larger of a^b or b^a in C++
- Minimum removals in a number to be divisible by 10 power raised to K in C++
- Show that:( left(x^{a-b}right)^{a+b}left(x^{b-c}right)^{b+c}left(x^{c-a}right)^{c+a}=1 )
- Prove that( frac{1}{1+x^{b-a}+x^{c-a}}+frac{1}{1+x^{a-b}+x^{c-b}}+frac{1}{1+x^{b-c}+x^{a-c}}=1 )
- Show that:( left(frac{x^{a^{2}+b^{2}}}{x^{a b}}right)^{a+b}left(frac{x^{b^{2}+c^{2}}}{x^{b c}}right)^{b+c}left(frac{x^{c^{2}+a^{2}}}{x^{a c}}right)^{a+c}= x^{2left(a^{3}+b^{3}+c^{3}right)} )
- Program to find Nth term divisible by a or b in C++

Advertisements