Friday, February 24, 2012

logic needed

Hi pundits,

I need a logic for solving a realtime issue.

I have series 2^0,2^1,2^2,......2^n ( i.e 1,2,4,8,16....2^n)

I want to write a function(algorithm) which returns all the terms used(added) to form the number

e.g fun(7) :-1,2,4
fun(5) :-1,4
fun(257):-1,256
fun(6):-2,4

Ur help is highly appreciated.

Thanks in advance.you can use bitwise and to check for this.

declare @.i int
set @.i=257
select * from (
select @.i & 1 as b union all
select @.i & 2 union all
select @.i & 4 union all
select @.i & 8 union all
select @.i & 16 union all
select @.i & 32 union all
select @.i & 64 union all
select @.i & 128 union all
select @.i & 256 ) a
where a.b > 0

No comments:

Post a Comment