Ruud H.G. van Tol on Sat, 14 Jan 2023 20:39:35 +0100 |
[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]
Re: probable bug of "ispower" function in GP: FALSE, apologies! |
On 2023-01-12 13:13, Karim Belabas wrote:
* Vincent Lefevre [2023-01-12 12:40]:On 2023-01-12 12:31:09 +0100, luis.gallardo@math.cnrs.fr wrote:I misunderstood the definition of "ispower"!I wanted a function that identify directly if some integer is a power of 2I suppose that you can use something like ispower(64,,&n) and check that n is 2. But I suppose that for large numbers, this may be inefficient because ispower() will not just check for powers of 2.Use hammingweight(N) == 1. Or v = valuation(N,2); N >> v == 1 if you need the exact power. (Will be a little slower.)
Just meant for inspiration, not as effective implementations:is_power_of1(n,p) = my(f=factor(n)); if(1==#f~, if(p==f[1,1],f[1,2],-oo), +oo)
is_power_of2(n,p)= my(r=valuation(n,p)); if(n==p^r,r,+oo) ? is_power_of1(32,2) %= 5 ? is_power_of2(32,2) %= 5 ? is_power_of1(27,2) %= -oo /* as 2 is not even a factor */ ? is_power_of2(27,2) %= +oo ? is_power_of1(54,2) %= +oo ? is_power_of2(54,2) %= +oo ? is_power_of1(1,10) %= +oo /* BUG */ ? is_power_of2(1,10) %= 0 -- Greetings, Ruud xxx