- Related Questions & Answers
- Find the multiple of x which is closest to a^b in C++
- Larger of a^b or b^a in C++
- K-th digit in ‘a’ raised to power ‘b’ in C++
- Bash program to find A to the power B?
- Minimum positive integer value possible of X for given A and B in X = P*A + Q*B in C++
- Program to find N-th term of series a, b, b, c, c, c…in C++
- Program to find Nth term divisible by a or b in C++
- Find minimum positive integer x such that a(x^2) + b(x) + c >= k in C++
- Count of all possible values of X such that A % X = B in C++
- Find 2^(2^A) % B in C++
- Find a palindromic string B such that given String A is a subsequence of B in C++
- Check if a number can be expressed as x^y (x raised to power y) in C++
- Find all pairs (a, b) in an array such that a % b = k in C++
- Minimum Flips to Make a OR b Equal to c in C++
- Print values of ‘a’ in equation (a+b) <= n and a+b is divisible by x

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have three values, a, b and x. We have to find one multiple of x, that is nearest to a^{b}. Suppose the numbers are x = 4, a = 3, b = 3, then the output will be 28, as this is nearest to 3^{3} = 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

#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); }

Nearest multiple: 28

Advertisements