

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Find the multiple of x which is closest to a^b in C++
Suppose we have three integers, a, b and x. The task is to get the multiple of x, which is closest to ab. So if a = 5, b = 4 and x = 3, then output will be 624. As 54 = 625, and 624 is the multiple of 3, which is closest to 625.
The task is simple. we have to follow these steps to solve this problem −
- calculate num := ab
- Then find f := floor of (num/x)
- Now the closest element at the left will be cl = x * f, and at right will be cr = x * (f + 1)
- Finally, the closest number among them will be min(num – cl, cr – num)
Example
#include <iostream> #include <cmath> using namespace std; long long getClosest(int a, int b, int x) { long long num = pow(a, b); int f = floor(num / x); long long cl = x * f; long long cr = x * (f + 1); if ((num - cl) < (cr - num)) return cl; else return cr; } int main() { int a = 5, b = 4, x = 3; cout << "Find closest element: " << getClosest(a, b, x); }
Output
Find closest element: 624
- Related Questions & Answers
- Find multiple of x closest to or a ^ b (a raised to power b) in C++
- Find number from given list for which value of the function is closest to A in C++
- Find ΔX which is added to numerator and denominator both of fraction (a/b) to convert it to another fraction (c/d) in C++
- C++ program to find ΔX which is added to numerator and denominator both of fraction (a/b) to convert it to another fraction (c/d)
- Find minimum positive integer x such that a(x^2) + b(x) + c >= k in C++
- Print values of ‘a’ in equation (a+b) <= n and a+b is divisible by x
- Minimum positive integer value possible of X for given A and B in X = P*A + Q*B in C++
- Count of all possible values of X such that A % X = B in C++
- Find First element in AP which is multiple of given Prime in C++
- Find First element in AP which is multiple of given Prime in Python
- Find the Closest Palindrome in C++
- Program to find nth term of a sequence which are divisible by a, b, c in Python
- Find a palindromic string B such that given String A is a subsequence of B in C++
- Find the closest value of an array in JavaScript
- Check if N is divisible by a number which is composed of the digits from the set {A, B} in Python
Advertisements