Randomly finding a number from the series 1, 2, 3... n to make it m

Source: Internet
Author: User

Using the knowledge of permutation and combination, we can calculate that n bit can represent 2 ^ n cases, for example, 3 bit can represent 8 conditions:
000 001 010 011 100 101 110 111
Now we stipulate that in the n bits, if this bit is 1, then from right to left, how many BITs is this bit: Suppose it is t, then t is selected: for example: in 110, 3 and 2 are selected, and 1 is not selected.
The specific implementation algorithm is as follows:
[Java]
Public static void getNM (int n, int m)
{


Int num = 1 <n;
For (int I = 1; I <= num; I ++)
{
Int sum = 0;
For (int j = I, k = 1; j> 0; j = j> 1, k ++)
{
If (j & 1) = 1)
{
Sum + = k;
}
}

If (sum = m)
{
Int val = 1;
For (int k = I; k> 0; k = k> 1, val ++)
{
If (k & 1) = 1)
{
System. out. print (val + "");
}
}
System. out. println ();
}
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.