Reputation: 25
I need to find the highest integer x (x > 1) so that 2^x <= n (n is input from keyboard).
I wrote this but it loops forever
#include <cmath>
...
double x, result;
x = 2.0;
result = pow(2.0, x);
while (result <= n) {
x++;
}
cout << x;
...
Upvotes: 1
Views: 402
Reputation:
must guard it to ensure correct result with test,
//..
#include <cmath>
using namespace std;
double result, x = 1.0,
n = 8;
while ((result=pow(2.0, x)) < n)
x++;
if (result > n) x--;
cout << x <<"\n"; // with sample n = 8 or 8.7 etc as well
3
Upvotes: 2
Reputation: 1221
Adding code to @David's answer. This is how you should update result
in loop, so that your existing infinite loop terminates.
//Assuming n is initialized somewhere else.
double x, result;
x = 0.0;
result = 0.0; //Initialize Result variable first, so that while loop condition passes.
while (result <= n)
{
x++;
result = pow(2.0, x + 1);
}
cout << x; // x contains exponent of 2
//result contains next 2 raise to power greater than n
Moreover, Since you're calculating max power of 2 which is less than to equal to n. Another way to do same:
int x = log2(n);
Yet another way to do this via bit shifting:
int x;
for (x = 0; 1 << (x + 1) <= n; x++);
// Same as before : x contains exponent of 2
UPDATE : Edited answer to address issue mentioned in comments. Thanks to @Adrian, I realized my silly mistake.
Upvotes: 2
Reputation: 238341
I wrote this but it loops forever
while (result <= n) { x++; }
Here is an analogy:
You stack antique clocks into a box. You've been instructed to stop stacking when the box contains ten marshmallows. How much time will it take for you to complete that task? Answer: Infinitely long, because what you're doing does not have an effect on the condition of stopping the repetition.
Your program has the same problem: The loop repeats until result <= n
is false. But the loop modifies neither variable, so therefore if the loop is ever entered, then it will never stop.
Upvotes: 3
Reputation: 182761
You need to update the value of result
in the loop, not just once before you start the loop.
Upvotes: 4