how to find whether a number is a power of 2. without using any Loops.
using namespace std;
cout<<"enter a no"<<endl;
float k=(float)(log (i)/log(2));
k=k%j;//------------------error-------… "%" cann`t take float vlaue.
cout<<"no "<<i<" is a power of 2"<<endl;
cout<<"sorry ! i am afraid "<<i<<" is not a power of 2"<<endl;
i tried this but error.
i stuck in one more problem weather a result is integer or not.
i have a logic for that.
if we find the log of that no (of the base 2), then if the result is equivalent to a integer then the no is of a power of 2.
that`s what i try to do in my original question. so if you can find a result is a integer not a decimal number, then we can solve it without loops.
Just think to yourself this, how does a exponent work.
The same way to build it up is the same way to break it down, if you think otherwise you need to study basic math.
1. Input a number as an int (as you're doing)
2. Cast the number to double in your log calculation and store the result of the calculation in a double variable.
double calcVal = log((double)num)/log(2.0);
3. Create an int version of the result from the above calculation.
int calcVal2 = (int)calcVal;
4. Subtract the int from the double, leaving you with the decimal remainder. (0.00003454865..or whatever)
double decimal = calcVal - calcVal2;
5. Multiply the decimal remainder by something like 100000 or so and store the final value as an int. This will truncate the later decimal places, from the remainder thereby avoiding the inherent problems with floating point arithmetic.
int final = (int)(decimal*1000000);
6. If the final value is 0, then your number is a power of two.
Cheers for now,
Edited 6 Years Ago by JasonHippy: smelling pistake
Help! I want to create a java program that finds the highest even integer among the values entered by the user. Stop asking values when a value less than 1 have been entered. If no even integer is entered, display "No Even Integer"
Hi, as I was told that my code doesn’t scale well at all, I thought perhaps I’d try to get a better understanding of interfaces/abstract classes and classes and the relationship between them.
I don’t want at this stage work on a big separate project as I've already got plenty ...