问题
This is a simple number series question, I have numbers in series like
2,4,8,16,32,64,128,256
these numbers are formed by 2,2(square),2(cube)
and so on.
Now if I add 2+4+8 = 14
. 14
will get only by the addition 2,4 and 8.
so i have 14
in my hand now, By some logic i need to get the values which are helped to get 14
Example:
2+4+8 = 14
14(some logic) = 2,4,8.
回答1:
This is an easy one:
2+4+8=14 ... 14+2=16
2+4+8+16=30 ... 30+2=32
2+4+8+16+32=62 ... 62+2=64
So you just need to add 2 to your sum, then calculate ld (binary logarithm), and then subtract 1. This gives you the number of elements of your sequence you need to add up.
e.g. in PHP:
$target=14;
$count=log($target+2)/log(2)-1;
echo $count;
gives 3, so you have to add the first 3 elements of your sequence to get 14.
回答2:
Check the following C# code:
x = 14; // In your case
indices = new List<int>();
for (var i = 31; i >= i; i--)
{
var pow = Math.Pow(2, i);
if x - pow >= 0)
{
indices.Add(pow);
x -= pow;
}
}
indices.Reverse();
回答3:
assuming C:
unsigned int a = 14;
while( a>>=1)
{
printf("%d ", a+1);
}
回答4:
if this is programming, something like this would suffice:
int myval = 14;
int maxval = 256;
string elements = "";
for (int i = 1; i <= maxval; i*=2)
{
if ((myval & i) != 0)
elements += "," + i.ToString();
}
回答5:
Use congruency module 2-powers: 14 mod 2 = 0
, 14 mod 4 = 2
, 14 mod 8 = 6
, 14 mod 16 = 14
, 14 mod 32 = 14
...
The differences of this sequence are the numbers you look for 2 - 0 = 2
, 6 - 2 = 4
, 14 - 6 = 8
, 14 - 14 = 0
, ...
It's called the p-adic representation and is formally a bit more difficult to explain, but I hope this gives you an idea for an algorithm.
来源:https://stackoverflow.com/questions/9291308/simple-number-series