Codechef Long 16 May

I was trying to solve Chef and amazingness problem but couldn’t think of any approach to solve large test cases . If any one if free to explain the idea please help me with it, link to the problem statement -> https://www.codechef.com/MAY16/problems/CHEFNUM . I can see some kind of bitmasking is done but not able to figure out anything.