Someone asked me a question yesterday ~ In the 500 Integers of 500, find the number of continuous addition equal to 500?
In fact, this is a very simple interview question. Why do some people prefer not to solve it by themselves? I think the most important thing is that many people do not like to use their brains. I have offended many people. Haha.
Brief Analysis: int [] X = {1, 2, I ,............ 499}
Condition: I + (I + 1) + ...... + (I + k) = 500 (1 type)
Use the Sum Formula of the same deviation series: (k + 1) * I + (k + 1) * k/2 = 500 (2 formula)
I and k have a hidden relationship. I * k <500 (3)
Therefore, we naturally obtain the following solution:
Private static void GetSomeInt (int maxInt)
{
For (int I = 1; I <(maxInt-1); I ++)
{
For (int k = 1; k <(maxInt/I); k ++)
{
If (k + 1) * I + k * (k + 1)/2) = maxInt)
{
/******************* Output result set ***************** ****/
String result = "xi = ";
For (int s = 0; s <(k + 1); s ++)
{
Result + = (I + s). ToString () + ";";
}
Result = result. TrimEnd (';');
Console. WriteLine (result );
/*************************************** *********/
}
}
}
}
Result:
Xi = 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19; 20; 21; 22; 23; 24; 25; 26; 27; 28; 29; 30; 31; 32
Xi = 59; 60; 61; 62; 63; 64; 65; 66
Xi = 98; 99; 100; 101; 102
According to eaglet, the performance of this algorithm is poor. Refer to its algorithm and modify it as follows:
Private static void GetSomeIntStep (int maxInt)
{
Int num = 0;
Int fnum = 0; // Convert. ToInt32 (System. Math. Sqrt (maxInt ));
Int tmp = maxInt-fnum * (fnum + 1)/2;
While (tmp> 0 ))
{
If (tmp % (fnum + 1) = 0) // source (k + 1) * I + k * (k + 1)/2) = maxInt
{
/******************* Output result set ***************** ****/
String result = "xi = ";
Int nn = tmp/(fnum + 1 );
For (int s = nn; s <(nn + (fnum + 1); s ++)
{
Result + = (s). ToString () + ";";
}
Result = result. TrimEnd (';');
Console. WriteLine (result );
/*************************************** *********/
Num ++;
}
Fnum ++;
Tmp = maxInt-fnum * (fnum + 1)/2;
}
Console. WriteLine ("cycles: {0}", fnum. ToString ());
}
In addition, according to the conditions,
(K + 1) k <2 * maxInt, which can be obtained (k + 1) (k + 1) <2 * maxInt (4 type)
We can propose a continuous integer of up to 32, so we can also use the following algorithm:
Private static void GetSomeIntThird (int maxInt)
{
Int num = 0;
Int maxnum = Convert. ToInt32 (System. Math. Sqrt (2 * maxInt); // (k + 1) Square <2 times of maxInt
For (int k = 1; k <= maxnum; k ++)
{
Int tmp = maxInt-k * (k + 1)/2;
If (tmp> 0 & tmp % (k + 1) = 0) // source (k + 1) * x + k * (k + 1)/2) = maxInt
{
/******************* Output result set ***************** ****/
String result = "xi = ";
Int x = tmp/(k + 1 );
For (int s = x; s <(x + k + 1); s ++)
{
Result + = (s). ToString () + ";";
}
Result = result. TrimEnd (';');
Console. WriteLine (result );
/*************************************** *********/
}
Num ++;
}
Console. WriteLine ("cycles: {0}", num. ToString ());
}