quote:
Original post by BloodScourge
As some of you said, the easiest way to figure out if a number m is a power of n is to perform :
pow=log(m)/log(n)
and if pow is an integer then m is a power of n.
Sorry for the old layout...
As has been pointed out in previous replies, ANY variation of the log(m)/log(n) solution to this problem won’t work, simply because these functions do not have the resolution to resolve between the values 34271896307633 and 34271896307632, for instance. I have tested this, even with double, it does not work.
The original problem suggested that being able to resolve between two large values like that was a requirement.
The solution to the problem:
bool PowerOf(unsigned hyper m, unsigned int n){ if (!n) return !m; unsigned hyper mTest = n; while (mTest < m) mTest *= n; return m == mTest;}
|
…is probably the best one (thanks to Kippesoep for tweaking the algo). The hyper type is a 64-bit integer, and this would give reliable results of values for m of up to 18,446,744,073,709,551,615. I don’t see that there can be a range problem here.
This is a perfect example of where floating point (any precision), is NOT the correct solution. Try any variation of it, and you'll see it's unreliable. I'm a firm believer in floating point, but there are rare cases where it's a bad idea.
Think about it for a while: You want to represent the values 34271896307633 and 34271896307632 each with a log value. The value is "compressed" into a much smaller range (due to the log curve). There's just no way to get the resolution to tell those numbers apart after you've taken their log.
Example:
log(34271896307633) = 13.534938135161013213941868837612
log(34271896307632) = 13.534938135161000541912343394266
That means you need to be accurate at least up to about 16 digits. This assumes the log function gave reliable results in the first place. The accuracy of double is only guaranteed up to 15 digits, so we see that this solution breaks down even before it gets to the values given for the original problem.
SS
Edited by - Axter on February 8, 2002 8:37:32 PM