I'm just trying to understand how this minimum power of 2 algorithm works, in particular, how this piece of code, result *= 2, returns the minimum power of 2 from the number entered by the user. I cannot seem to figure it out, even when I write it out manually. Any help to clarify would be greatly appreciated!
int main()
{
int userInput, result;
do
{
printf("Enter a number (-1 to exit): ");
scanf("%d", &userInput);
if (userInput > 0)
{
result = 1;
while (result < userInput)
{
result *= 2;
}
printf("Minimum power of 2 greater than %d: %d\n", userInput, result);
}
} while (userInput != -1);
return EXIT_SUCCESS;
}
Output when 3 is entered: Min.....3: 4
Output when 5 is entered: Min.....5: 8
CodePudding user response:
There are no problems with the implementation of this algorithm[1]. This algorithm returns the least power of 2, provided it is greater than or equal to the variable userInput:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int userInput, result;
do{
printf("Enter a number (-1 to exit): ");
scanf("%d", &userInput);
if (userInput > 0){
result = 1;
int counter = 0;
while (result < userInput){
result *= 2;
printf("Result: %d\t Counter: %d\n", result, counter );
}
printf("Result: %d ^ %d = %d\n", 2, counter, (int) pow(2, counter));
printf("Minimum power of 2 greater than %d: %d\n", userInput, result);
}
} while (userInput != -1);
return EXIT_SUCCESS;
}
In the above application, if the user enters the value 11, the following result is produced:
Enter a number (-1 to exit): 11
Result: 2 Counter: 0
Result: 4 Counter: 1
Result: 8 Counter: 2
Result: 16 Counter: 3
Result: 2 ^ 4 = 16
Minimum power of 2 greater than 11: 16
1 - Smallest power of 2 greater than or equal to n
CodePudding user response:
Change to this:
while (result < userInput)
{
printf("Before: %d\n");
result *= 2;
printf("After: %d\n\n");
}
And you'll see what's going on.
CodePudding user response:
...
result = 1;
while (result < userInput)
{
result *= 2;
}
...
Every time result is tested and it's lesser than userInput, result is doubled.
In the case of 5 as userInput
| iterations | result |
userInput |
|---|---|---|
| at start | 1 | 5 (>result so continue looping) |
| iteration 1 | 2 | 5 (>result so continue looping) |
| iteration 2 | 4 | 5 (>result so continue looping) |
| iteration 3 | 8 | 5 (<result so loop stops) |
