Programming beauty 2--n! The location of the lowest bit 1 in binary representation

Source: Internet
Author: User

Any number inside the computer is represented by a binary representation, which can be used to quickly determine the position of the lowest bit 1 in the binary representation of the n!.


Solution One:

Divides the binary number of a number by 2, and if the end of the binary number is 0, it can be divisible, otherwise it cannot be divisible.

Therefore, the position of the lowest bit 1 in the binary representation of n! is to find out how many factorization 2 are in n!


The following is code 1:

#include <iostream>using namespace Std;int main (void) {int n,m;m=0;cin>>n;while (n) {n>>=1;m+=n;}    cout<< m+1 <<endl; M is the number of n! factor 2, so the final result is to add 1return 0;}


Solution Two:

N! contains the number of factorization 2, equal to n (the number of 1 in the binary representation of N)

(This rule is self-proof)


Code Listing 2:

#include <iostream>using namespace Std;int main (void) {int n,i,j,m;    m=0;    j=0x1;    cin>>n;    I=n;    while (i) {m+= (i&j);i>>=1;    } cout << n-m+1 <<endl; M is the number of n! factor 2, so the final result is to add 1 return 0;


This article is from the "hacker" blog, make sure to keep this source http://anglecode.blog.51cto.com/5628271/1631147

Programming beauty 2--n! The location of the lowest bit 1 in binary representation

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.