Beautiful numbers

The beauty of a number is defined as the total number of '1's in the binary representation of the number.

Find the largest 3-digit number, which is as beautiful as '271'


The answer is 992.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

18 solutions

Discussions for this problem are now closed

Meet Udeshi
Dec 29, 2013

271 can be written as 271 = 256 + 8 + 4 + 2 + 1 = 10000111 1 2 271=256+8+4+2+1=100001111_2 It has a beauty of 5.

So we want the largest number less than 1000 with a beauty of 5. In other words we need the largest possible number less than 1000 which can be written as the sum of 5 different powers of 2

The largest power of 2 it can contain is 512, then 256, then 128 and so on...

So the number can be n = 512 + 256 + 128 + 64 + 32 = 992 n=512+256+128+64+32=992 We are lucky that the first number we guessed is less than 1000. That is the answer. Or else we would have to consider smaller numbers by adding 16 instead of 32, and so on...

wats the meaning of "it has beauty of 5"

Sajith Menon - 7 years, 5 months ago

It's just made up. It could have said, "It has a stinkiness of 5". It just means (in this problem) how many ones are in the binary representation of the number.

Finn Hulse - 7 years, 4 months ago

Use the following algorithm [SWAR], to calculate the number of set bits in any integer;

int SetBitCount(int i) { i = i - ((i >> 1) & 0x55555555); i = (i & 0x33333333) + ((i >> 2) & 0x33333333); return (((i + (i >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; }

riaz munshi - 7 years, 2 months ago
Elliot Kienzle
Dec 29, 2013

We can use the convenient Python method bin which converts an integer to a binary string in combination with Python's string method count to accomplish this task. First, we define a function beauty(x) like this:

def beauty(x):
  return bin(x).count("1")

Then, we evaluate beauty(271) and we get 5 5 , therefore we can write a loop that solves the problem:

num = 0
for x in range(100, 1000):
  if x > num and beauty(x) == 5:
    num = x

If we run this loop, we find that num is 992 992 .

An even easier method is to use a math programming language itself, like PARI/GP. The "beauty" of a number is already implemented itself, as the function hammingweight(x), so we just need to run the loop: for(n=100,1000,if(hammingweight(n)==5,print1(n",")))

Edward Jiang - 7 years, 5 months ago

I did this in PHP - logically it was similar, but the syntax was much messier. The more I see of Python the more I like it.

Joe Malt - 7 years, 5 months ago
Lokesh Sharma
Dec 27, 2013

Python Solution:

def digitSum(s):
    return sum([int(i) for i in s[2:]])

for i in range(1000)[::-1]:
    if digitSum(bin(271)) == digitSum(bin(i)):
        print i
        break

First note that 27 1 10 = 10000111 1 2 271_{10}=100001111_2 , which has a beauty of 5.

We seek a 3-digit number with a beauty of 5.

Now, note that this 3-digit number must be less than or equal to 99 9 10 = 111110011 1 2 999_{10}=1111100111_2 , but must have five 1's.

It is clear that the number we are seeking is 111110000 0 2 = 992 10 1111100000_2=\boxed{992}_{10}

minimario minimario - 7 years, 5 months ago

I can't really understand your method. Did you say "it is clear that..." by observing that you could change the last few 1's to 0's What if the question asked for a number less than 769 say. 76 8 10 = 110000000 0 2 768_{10}=1100000000_2 . How would your method apply to this one?

Meet Udeshi - 7 years, 5 months ago

You would change the 2nd number to a 0 and add 1's to the front, like so: 101111000 0 2 1011110000_2 to create the greatest number possible.

minimario minimario - 7 years, 5 months ago

Uh, the problem is categorized as computer science.

Daniel Chiu - 7 years, 5 months ago
Bernardo Sulzbach
Jun 18, 2014

Python 3.4.1

one_count = lambda number: bin(number).count('1')

target = one_count(271)

print(max([n if (one_count(n) == target) else 0 for n in range(271, 1000)]))

Amish Naidu
Mar 12, 2014

Solution in C++ :

    unsigned int binOnes(unsigned int n)
    {
        if(n < 2)
            return n;
        return (n%2) + binOnes(n/2);
    }
    int main()
    {
        int target = binOnes(271) , num;
        for(num = 999 ; binOnes(num) != target ; --num);
        cout << num << endl;
        return 0;
    }
Nimisha Soni
Feb 26, 2014

No. of ones in 271 (0000000 1 0000 1111) = 5 The first largest number with 5 ones till 9th bit can be

0 0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 =496

The above thing is checked because in this 9th bit is acting as MSB . Moving these ones to 10th bit i.e the next MSB like:

0 0 0 0 0 0 1 1 1 1 1 0 0 0 0 0  = 992

this is the largest number

for(i=0; cpyDecNumber>0; i++) { quotient = cpyDecNumber % 2; binaryArray1[i] = quotient; cpyDecNumber = cpyDecNumber / 2; } arrayIndex = i-1; j = arrayIndex; printf("\nBinary Equivalent of the given number is :\n"); while(j>=0) { if(binaryArray1[j] == 1) { beautyCounter++; } printf("%d", binaryArray1[j]); j = j-1; } beautyGiven = beautyCounter; printf("\nHence the Beauty of the given number is : %d\n", beautyGiven); printf("\nWe are processing for finding the largest 3-digit number with same beauty!\n");

for (j=8; j>(8-beautyGiven); j--)
{
    binaryArray2[j] = 1;
}
for(i=8; i>0; i--)
{
    printf("%d", binaryArray2[i]);
    sameBeauty = sameBeauty + ((pow(2,i+1))*binaryArray2[i]);
}
printf("\n%d", sameBeauty);
Srirama Krishnan
Feb 16, 2014

I have written the code in python:

Solution:

for i in xrange(999,99,-1):

    if bin(i)[2:].count('1') == 5:

        print i

        break

The answer is:

992

def beautiful(n):

binary=str(bin(n))[2:]

sum=0

for i in range(0,len(binary)):

    if int(binary[i])==1:

        sum = sum + int(binary[i])    

return sum

def smallest(digits):

if digits==1:

    return 1

return pow(10,digits-1)

def largest(digits):

return pow(10,digits)-1

def find beautiful as(asNumber,noOfDigits):

asNum=asNumber

for i in range(smallest(noOfDigits),largest(noOfDigits)):

    b = beautiful(i)

    if b==beautiful(asNum):

        asNum=i

return asNum

print find beautiful as(271,3)

Reaz Mahmud
Jan 26, 2014

include <stdio.h>

int main() { int i, j, a=0; for (i=999;i>99;i--) { for (j=i;j>0;j=j/2) { if (j%2==1) a++; } if (a==5) { printf("%d", i); break; } a=0;

} }

Ivan Dimitrov
Jan 18, 2014

answer = 992

#    x = 999
#    sumX = 0
#    while x > 271:
#        binaryX = bin(x)
#        for s in binaryX:
#            if s == '1':
#                sumX += 1
#        if ( sumX == 5):
#            print x
#            break
#        x = x - 1
#        sumX = 0
William Cui
Jan 16, 2014

This solution is purely mathematics - no programming.

27 1 10 = 10000111 1 2 271_{10}=100001111_2

which has 5 '1's.

We need to find the largest three-digit number with five ones. Note that we cannot go over 512, since 1024 is the next highest power of 2 and that is over 1000.

The largest we can go is therefore

512 + 256 + 128 + 64 + 32 = 992 512+256+128+64+32=992

Since we cannot go any larger and this number satisfies our conditions, our answer is 992 \boxed{992} \ \blacksquare

Defri Ahmad
Jan 10, 2014

for the first write 271 271 in binary representation that is 271 = 100001111 271=100001111 , so 271 271 beautiful as 5 5 Just find the largest n n such that 2 n < 1000 2^n<1000 that is n = 9 n=9 and then find the largest n n such that 2 n < 1000 2 9 2^n<1000-2^9 that is n = 8 n=8 and then find the largest n n such that 2 n < 1000 2 9 2 8 2^n<1000-2^9-2^8 that is n = 7 n=7 and then find the largest n n such that 2 n < 1000 2 9 2 8 2 7 2^n<1000-2^9-2^8-2^7 that is n = 6 n=6 and the fifth digit is find the largest n n such that 2 n < 1000 2 9 2 8 2 7 2 6 2^n<1000-2^9-2^8-2^7-2^6 we can use this method because 1 + 2 + 2 2 + . . . + 2 n 1 = 2 n 1 < 2 n 1+2+2^2 +...+2^{n-1}=2^n-1<2^n .

Vivek Kumar
Jan 5, 2014

solution

def to_bin(n): #converting a number to binary
    k=10     
    p=0
    while k>=0:
        if n/(2**k) >= 1:
            n=n-(2**k)
            p=p*10+1
        else:
            p=p*10
        k=k-1
    return p

def count_beauty(n): # counting beauty of n using its binary
    binofn=to_bin(n)
    beauty=0
    for ele in str(binofn):
            if ele=='1':
            beauty+=1

    return beauty

b=count_beauty(271)     # ''271''
number=1000             # counting backwards from 1000

while number>=0:
    if count_beauty(number)==b:
        print  number
        break
    number=number-1
Debjyoti Bhaumik
Jan 1, 2014

I simply used brute force to get the answer. My python code.

R = 271
target_beauty = bin(R).count('1')
for i in range(R,1000):
    beauty = bin(i).count('1')
    if beauty == target_beauty:
         if i > R:
            R = i
print(R)

R = 271
target_beauty = bin(R).count('1')
for i in range(R,1000):
    beauty = bin(i).count('1')
    if beauty == target_beauty and i > R:
        R = i
print(R)

Debjyoti Bhaumik - 7 years, 5 months ago
Hùng Minh
Dec 30, 2013

271 in the binary representation is 100001111. Sum of number of '1's is 5. So the largest 3-digit number must have sum of number of '1's is 5. The number 111110000 is 9 digits <=> In the decimal representation is 496. We try add 1 number 0 to the last, we have 1111100000 is 10 digits <=> In the decimal representation is 992. So the largest 3-digit number is 992

Mateo Torres
Dec 29, 2013

The interesting thing is to convert from decimal to binary, here is my C++ Code:

            void binary(int a)
            {
                vector <int> binary_vector;
                long binary_number, dividend;

                cout << "\nDecimal: " << a;
                dividend = a;

                while (dividend >= 1)
                {
                    binary_number = dividend % 2;
                    dividend /= 2; 
                    binary_vector.push_back(binary_number);
                }

                cout << " Binary: ";
                for (int i = binary_vector.size() - 1; i >= 0; i--)
                    cout << binary_vector[i];
            }

            int _tmain(int argc, _TCHAR* argv[])
            {
                int h, j;
                cin >> h;
                cin >> j;

                for (h; h > j; h--)
                {
                    binary(h);
                }

                _getch();

                return 0;
            }

I have also coded a similar algorithm... #include <iostream>

typedef unsigned int uint;

uint countBeauty(uint num, char* buffer){
    uint sz = sizeof(uint) * 8;

    uint sum;
    for (uint i = 0; i < sz; ++i, ++ch) {
    sum += (num << i) >> (sz - 1);
    }
    return sum;
}


//Returns buffer length...may be replaced with void
int toBinary(uint num, char* buffer){
    if(!buffer)
    return -1;
    char* ch= buffer;

    const static char bi[] = {'0','1'};
    uint sz = sizeof(uint) * 8;

    uint bit;
    for (uint i = 0; i < sz; ++i, ++ch) {
    *ch = bi[    (num << i) >> (sz - 1)    ];
    }

    *ch = '\0';
    return static_cast<int>(buffer - ch);
}

Debjyoti Bhaumik - 7 years, 5 months ago
Raghav Dua
Dec 29, 2013

//write include iostream statement, then write include string statement, then copy the code and paste

using namespace std;

typedef unsigned short int USHORT;

int toPower (const int number, const int exponent) {

if (number == 1 || exponent == 0) { return (1); }

else if (number == 0) { return (0); }

else if (exponent == 1) { return (number); }

else {

int buffer (number);

for (int i = 0; i < (exponent - 1); i++) {

  buffer *= number;

}

return (buffer);

}

}

int getMaxExponent (const int& number, const int base) {

int tester (0), counter (0);

while (tester <= number) {

++counter;

tester = (toPower (base, counter));

}

--counter;

return (counter);

}

string convertToBin (int usrInput) {

string subject;

int buffer (0), resultLength (0), counter (0);

int maxExponent = getMaxExponent (usrInput, 2);

while (maxExponent > -1) {

buffer = toPower (2, maxExponent);

if (usrInput >= buffer) {

  usrInput -= buffer;

  subject += "1";

}

else {

  subject += "0";

}

--maxExponent;

}

return (subject);

}

int main (int argc, char* argv []) {

const int numBeauty (5);

int counter (0), greatest (0), resultLength (0);

string result;

for (int i = 100; i <= 999; i++) {

if (i == 271) { continue; }

else {

  result = convertToBin (i);

  for (int j = 0; j < (result.length ()); j++) {

if (result [j] == '1') { counter++; }

  }

  if (counter == numBeauty && (i > greatest)) {

greatest = i;

  }

  counter = 0;

}

}

cout << greatest << endl;

return (0);

}

Here is a solution in C#. FindMax is a custom iterative function. (body not listed.)

        int cn = 0;
        int sn = 0;
        string si = String.Empty;
        string sit = String.Empty;
        ArrayList ar = new ArrayList();

        sit = GetIntBinaryString(271);

        for (int k = 0; k < sit.Length; k++)
        {
            sn += int.Parse(sit[k].ToString());
        }


        for (int i = 0; i < 999; i++)
        {
            try
            {
                si = GetIntBinaryString(i);

                for (int k = 0; k < si.Length; k++)
                {
                    cn += int.Parse(si[k].ToString());
                }

                if (cn == 5)
                {
                    ar.Add(i);
                }

                cn = 0;
            }
            catch
            {
            }
        }

        MessageBox.Show(FindMax(ar).ToString());

Sanjay kamath - 7 years, 3 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...