Lucky Numbers

Let's say that a number k is "lucky" if it has the following characteristics:

  • It has 6 digits

  • The sum of its first three digits is equal to the sum of its last three digits

Let N be the total number of positive 6-digit "lucky" numbers. What are the last three digits of N ?


The answer is 412.

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.

33 solutions

Jubayer Nirjhor
Dec 14, 2013

Here's a Python solution... Someone please show me how to create that ash colored codish background... :/

Answer = 0 \text{Answer = 0}

for p in range (100000, 1000000): \text{for p in range (100000, 1000000):}

lst = [int(i) for i in str(p)] ~~~~~~~~\text{lst = [int(i) for i in str(p)]}

if lst[0] + lst[1] + lst[2] == lst[3] + lst[4] + lst[5]: ~~~~~~~~\text{if lst[0] + lst[1] + lst[2] == lst[3] + lst[4] + lst[5]:}

Answer += 1 ~~~~~~~~~~~~~~~~\text{Answer += 1}

print Answer \text{print Answer}

All problems on Brilliant have a relatively small Python code it seems! :D

Kou$htav Chakrabarty - 7 years, 3 months ago

indent the code lines by 4 spaces

Josh Silverman Staff - 7 years, 6 months ago

Log in to reply

Thanks!!! :D

Jubayer Nirjhor - 7 years, 6 months ago

Log in to reply

haha

Josh Silverman Staff - 7 years, 6 months ago

Here, I rewrote the code in ash back... Thanks to Josh Silverman , Daniel Chiu and Sreejato Bhattacharya :)

1
2
3
4
5
6
7
8
Answer = 0

for p in range (100000, 1000000):
    lst = [int(i) for i in str(p)]
    if lst[0] + lst[1] + lst[2] == lst[3] + lst[4] + lst[5]:
        Answer += 1

print Answer

Output: 50412 50412

Implying the answer to be: 412 \fbox{412}

Jubayer Nirjhor - 7 years, 6 months ago

Log in to reply

Why are you thanking me? :O

Sreejato Bhattacharya - 7 years, 6 months ago

Log in to reply

For your concern... O:)

Jubayer Nirjhor - 7 years, 6 months ago

Pretty good, but next time use xrange instead of range. It works the same way, but range creates a list from 100000 to 1000000 (in your case) which takes a lot of cpu and computer memory and CPU, while xrange starts at 100000 and goes to 100001, and so on, just going to the next number until it reaches 1000000.

Giorgian Borca-Tasciuc - 7 years, 1 month ago

use 4 spaces before each line of code and make the code block a paragraph by leaving a blank line on top and bottom . You will find the ash colored bg.

Tanmay Meher - 7 years, 1 month ago

Done in C++

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
int main(){
    int total = 0;
    int array[6];
    for(int i = 100000; i < 1000000;i++){
        int num = i;
        for(int j = 0; j < 7; j++){
            array[j] = num%10;
            num /= 10;
        }
        if(array[0]+array[1]+array[2]==array[3]+array[4]+array[5]){
            total++;
        }
    }
    printf("the max is %d", total);
} 

FanPu Zeng - 7 years, 2 months ago
Daniel Chiu
Dec 13, 2013

Loop through all possible values for each digit, only 9 1 0 5 9\cdot 10^5 possibilities. This can be achieved with a few for loops, and one if statement checking if the sum of the first 3 digits is the same as the sum of the last 3.

Python code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
count = 0
for a in range(1,10):
    for b in range(0,10):
        for c in range(0,10):
            for d in range(0,10):
                for e in range(0,10):
                    for f in range(0,10):
                        if (a+b+c==d+e+f):
                            count+=1
print count

gives 50 412 50\boxed{412} .

You could have made your code more efficient by running the loop for d d in the range ( 0 , a + b + c + 1 ) (0, a+b+c+1) , and the loop for e e in the range ( 0 , a + b + c d + 1 ) (0, a+b+c-d+1) . Note that each valid selection of ( d , e ) (d,e) corresponds to a unique f f . Otherwise, that's how I did it. :)

Sreejato Bhattacharya - 7 years, 6 months ago

Log in to reply

Well, that isn't always more efficient, as a + b + c + 1 a+b+c+1 could be greater than 10, and similarly for the other one. The f f thing is a good idea.

Either way, efficiency wasn't needed, and I just tried to solve the problem as quickly as possible.

Daniel Chiu - 7 years, 6 months ago

Log in to reply

Yeah, missed it! I guess we can define a function min \min which takes two numbers and returns their minimum, and run the loop from 0 0 to min ( 10 , a + b + c ) + 1 \min (10, a+b+c)+1 . Note that efficiency does matter here (afaik that's the reason why the CS section in Brilliant was shut down for a while).

Sreejato Bhattacharya - 7 years, 6 months ago

Log in to reply

@Sreejato Bhattacharya Well, I mean no optimization was necessary.

Also, I think min can be used after importing math.

Daniel Chiu - 7 years, 6 months ago

How did you create that ash colored codish back??? I couldn't do it... :/

Jubayer Nirjhor - 7 years, 6 months ago

Log in to reply

Indent every line by four spaces.

Daniel Chiu - 7 years, 6 months ago

Log in to reply

Thank you!!! ;) :D :)

Jubayer Nirjhor - 7 years, 6 months ago

Another way, to use generating function:

In maxima or any other CAS:

 expand(sum(x^i,i,1,9)*sum(x^i,i,0,9)^2*sum(1/x^i,i,0,9)^3);

Answer is the constant term.

gopinath no - 7 years, 5 months ago

Excuse me. do you have a facebook account or an E-mail so i can contact with you ?

Abdallah Ismail - 7 years, 5 months ago

Great use of nested for loops to get the answer.

A Former Brilliant Member - 7 years, 5 months ago

I did exactly same but in C++ :D

Kou$htav Chakrabarty - 7 years, 3 months ago
Luke Nelson
Dec 14, 2013

counter=0
for x in range (100000,1000000):
y=str(x)
if int(y[0])+int(y[1])+int(y[2])==int(y[3])+int(y[4])+int(y[5]):
counter+=1



print(str(counter)[-3:])

Anubhav Singh
Dec 14, 2013

Here is a java Program for this question

 1
 2
 3
 4
 5
 6
 7
 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
33
class sum
{
void main()
{

int a=0,f=0,h=0,s=0;
for(int i=100000;i<=999999;i++)
{f=i;
for(int j=1;j<=3;j++)
{

int b=f%10;
a=a+b;
f=f/10;
}
for(int v=1;v<=3;v++)
{

int b=f%10;
h=h+b;
f=f/10;
}
if(a==h)
{
s=s+1;
}
a=0;
f=0;
h=0;
}
System.out.println(s);
}
} 

Cool! I did it exactly like that!

David Kroell - 7 years, 5 months ago

PHP version

            $first = 100000;
            $last = 999999;
            $count = 0;

            for($i = $first; $i<= $last; $i++){
                $temp = $i;
                $fir = $i % 10; $i = $i / 10;
                $sec = $i % 10; $i = $i / 10;
                $thir = $i % 10; $i = $i / 10;
                $fort = $i % 10; $i = $i / 10;
                $fif = $i % 10; $i = $i / 10;
                $six = $i % 10; $i = $i / 10;
                $i = $temp;
                $firstSum = ($fir + $sec + $thir);
                $secSum = ($fort + $fif + $six);

                if($firstSum == $secSum){

                    $count++;
                }
            }
            print($count);

Sarath CP - 7 years, 5 months ago
Robin Kumar
Feb 24, 2014

public class LuckyNumbers {

/**
 * @param args
 */
public static void main(String[] args) {
    int count = 0;
    for (int i = 100000; i <= 999999; i++)
        if (isLucky(i))
            count++;
    System.out.println(count % 1000);

}

static boolean isLucky(int n) {
    int s1 = 0, s2 = 0;
    for (int i = 1; i <= 3; i++) {
        s1 += n % 10;
        n /= 10;
    }
    for (int i = 1; i <= 3; i++) {
        s2 += n % 10;
        n /= 10;
    }
    if (s1 == s2)
        return true;
    else
        return false;
}

}

Mihir Garimella
Jan 8, 2014

While there's probably a more efficient way to do this problem, it's extremely easy if you use six nested for loops (ie. one for each digit). Here's a quick Javascript program to find N ("total number of positive 6-digit 'lucky' numbers"):

var n = 0;

for (var first = 1; first <= 9; first++) {
    for (var second = 0; second <= 9; second++) {
        for (var third = 0; third <= 9; third++) {
            for (var fourth = 0; fourth <= 9; fourth++) {
                for (var fifth = 0; fifth <= 9; fifth++) {
                    for (var sixth = 0; sixth <= 9; sixth++) {
                        if ((first + second + third) == (fourth + fifth + sixth)) {
                            n++;
                        }
                    }
                }
            }
        }
    }
}

console.log(n);
Anis Abboud
Dec 14, 2013

The following code returns 50412 \boxed{50412} .

def SumDigits(x):
    result = 0
    while x > 0:
        result += x % 10
        x /= 10
    return result 

count = 0
for k in range(100000, 1000000):
    if SumDigits(k % 1000) == SumDigits(k / 1000):
        count += 1

print count
Talha Butt
Dec 17, 2015

Solution in python 3:

lower_limit = 1 * (10**5)
upper_limit = (lower_limit * 10)

def iter_digits(number):
    if number:
        yield number % 10
        yield from iter_digits(number // 10)

def is_lucky(digits):
    return sum((digit if i < 3 else digit * -1) for i, digit in enumerate(digits)) == 0

N = sum(1 for number in range(lower_limit, upper_limit) if is_lucky(iter_digits(number)))

print(N) # Outputs 50412
David Holcer
Mar 21, 2015
1
2
3
4
5
6
summ=0
for i in range(10**5,10**6):
    i=str(i)
    if int(i[0])+int(i[1])+int(i[2])==int(i[3])+int(i[4])+int(i[5]):
        summ+=1
print str(summ)[-3:]

Tanmay Meher
May 5, 2014

Python solution

count = 0
for i in range(100000,1000000):
        if sum(map(int,str(i)[:3])) == sum(map(int,str(i)[3:])):
                count += 1
print count

map is a built-in python function. Usage : map( function , iterable , ...) which apply function to every item of iterable and return a list of the results.

Kavish Gandhi
Apr 24, 2014

Python (somewhat efficient):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def sum(threedigit):
    return three%10 + three/100 + (three/10)%10

count = 0
for i in range(100000, 1000000):
    k = i/1000
    j = i%1000
    if sum(j)==sum(k):
        count+=1

print count

Connor Kenway
Apr 10, 2014

include <iostream>

using namespace std;

int main() 
{
    int count=0;
    for(int i=100000;i<=999999;i++)
    {
        int sum=0,sum2=0;
        int j=i,l=i/1000;
            for(int k=1;k<=3;k++)
            {
                    sum+=j%10;
                j=j/10;
                sum2+=l%10;
                l=l/10;
            }
        if(sum==sum2)
        count++;
    }
    cout<<count;
}
Sandeep Thakur
Mar 25, 2014

Here is Javascript Solution

count = 0;
for(num=100000; num<=999999; num++){
    a = num.toString().split('').map(function(e){ return parseInt(e); });
    if(a[0] + a[1] + a[2] == a[3] + a[4] + a[5])
        count++;
}
console.log(count);
Vaibhav Zambad
Mar 21, 2014

The following Python code solves the given problem:-

a=100000

b=999999

c=0

d=0

number=0

while(a<=b):

e=a

f=str(e)

g=f[0]

h=int(g)

i=f[1]

j=int(i)

k=f[2]

l=int(k)

first_three=h+j+l

m=f[3]

n=int(m)

o=f[4]

p=int(o)

q=f[5]

r=int(q)

last_three=n+p+r

if(first_three==last_three):

    number=number+1

a+=1

print number

Here ,the number prints all the 6-digit numbers starting from 100000 to 999999 and whose sum of first three digit number is same as that of last three digit numbers...so,number=50412 and the last three digits are 412 which is the answer

Ryan Braam
Mar 15, 2014

The modulus operator can be used creatively to isolate the digits for solving this problem. An example of such is shown in the Python script below.

count = 0
for i in range(100000,1000000):
    first = ( (i - (i%100000)) / 100000)
    temp = i%100000
    second = ( (temp - (temp%10000)) / 10000)
    temp = i%10000
    third = ( (temp - (temp%1000)) / 1000)
    temp = i%1000
    fourth = ( (temp - (temp%100)) / 100)
    temp = i%100
    fifth = ( (temp - (temp%10)) / 10)
    sixth = i%10
    if first+second+third == fourth+fifth+sixth:
        count += 1
print count

Snakes, Snakes everywhere

def findSumOfDigits(number):
    return sum([int(number) for number in list(str(number))])

nos=0
for index in range(100000,1000000):
    if(findSumOfDigits(int(str(index)[:3]))==findSumOfDigits(int(str(index)[-3:]))):
        nos=nos+1

print findSumOfDigits(int(str(nos)[-3:]))
Vaibhav Jain
Mar 9, 2014

a=[]

count =0

for i in range (100000,1000000):

a=str(i)

b=int(a[0])+int(a[1])+int(a[2])

c=int(a[3])+int(a[4])+int(a[5])

if(b==c):

    count = count +1

print count

Samarth Bhargav
Mar 1, 2014

Here's what I did:

def isLucky(num):
    s = str(num)
    if len(s) == 6 and sum([int(x) for x in s[:3]]) == sum([ int(y) for y in s[3:]]):
        return True
    return False


start = 100000
end =   1000000
count = 0
while start < end:
    if isLucky(start):
        count+= 1

    start+=1

Here's my solution in C++:

#include <iostream>

using namespace std;

int main()
{
    int counter = 0;

    long I;
    int J;

    for(I = 100000; I <= 999999; I++)
    {
        long digits[6], temp = I;

        for(J = 5; J >= 0; J--)
        {
            digits[J] = I % 10;
            I /= 10;
        }

        I = temp;

        int first_sum = digits[0] + digits[1] + digits[2];
        int second_sum = digits[3] + digits[4] + digits[5];

        if(first_sum == second_sum)
        {
            //cout << I << endl;
            counter++;
        }
    }

    cout << endl << counter << endl;

    return 0;
}

Output

50412 .

Hence the last 3-digits are 412 \boxed{412} .

Ashish Kant
Feb 26, 2014

int n=0,a,b,c=0,d=0; int suma,sumb; for(int i=100000;i<=999999;i++){ a=i/1000; b=i%1000; //System.out.println(a); //System.out.println(b); while(a>0){ c+=a%10; a=a/10;

        }
        while(b>0){
            d+=b%10;
            b=b/10;

        }
        if(c==d){
            n++;
        }
        c=0;
        d=0;
    }
    System.out.println(n);

def lucky_num():

number = 99999
first = ""
last = ""
count = 0
while number < 999999:
    number = number + 1
    if len(str(number)) == 6:
        first = str(number)[0:3]
        last = str(number)[3:6]
        num1 = 0
        num2 = 0
        for j in first:
            num1 = num1 + int(j)
        for k in last:
            num2 = num2 + int(k)
    if num1 == num2:
        count = count + 1
print count

too long not very good solution :P but it works

while(i<999999) { j = i; un = j % 10;

        j = j / 10;
        de = j % 10;

        j = j / 10;
        hu = j % 10;

        j = j / 10;
        th = j % 10;

        j = j /10;
        teth = j % 10;

        j = j /10;
        la = j % 10;

        lastThree = un + de + hu;
        firstThree = th + teth + la;

        if(lastThree == firstThree)
        {
            counter++;
        }
        i = i + 1;

    }
    System.out.println("Number of Lucky Numbers" + counter);
Otávio Augusto
Feb 13, 2014

Code for VB.Net:

Public Class Form1

Dim contLuckyNumbers As Integer

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim str As String = ""
    Dim part1, part2 As Integer
    For n = 100000 To 999999
        str = n.ToString
        part1 = CInt(str.Substring(0, 1)) + CInt(str.Substring(1, 1)) + CInt(str.Substring(2, 1))
        part2 = CInt(str.Substring(3, 1)) + CInt(str.Substring(4, 1)) + CInt(str.Substring(5, 1))
        If part1 = part2 Then
            contLuckyNumbers = contLuckyNumbers + 1
        End If
    Next
    Label1.Text = contLuckyNumbers.ToString
End Sub

End Class

Forgive my inelegant code:

count = 0
for i in range(100000,1000000):
    if int(str(i)[0])+int(str(i)[1])+int(str(i)[2]) == int(str(i)[3])+int(str(i)[4])+int(str(i)[5]):
        count += 1
print count

>>> 50412

Therefore the answer is 412 \boxed{412}

William Zhang
Dec 30, 2013

Write this in python

def firstsum(n):

    s=0

    n=n//1000

    for i in range(3):

        r=n%10

        n=n//10

        s=s+r

    return s

def lastsum(m):

    a=0

    for j in range(3):

        a=a+m%10

        m=m//10

    return a

b=0

for i in range(100000, 1000000):

    if firstsum(i)==lastsum(i):

        b=b+1

print(b)
Rithvik Pasumarty
Dec 27, 2013

Code in Java...

public class DigitSum{
public static void main(String[] args){
    int luckyCount = 0;
    int tempDigit1, tempDigit2, tempDigit3, tempDigit4, tempDigit5, tempDigit6, tempI;
            //loops through all of the six digit numbers
            //we take mod 10 to find the individual digits
    for(int i=100000; i<=999999; i++){
                    //temporary digits are used as we want to see if the sum of the digits are equal
        tempDigit1 = i%10;
                    //a temporary i is used so that the loop counter doesn't get confused
        tempI = i/10;
        tempDigit2 = tempI%10;
        tempI = tempI/10;
        tempDigit3 = tempI%10;
        tempI = tempI/10;
        tempDigit4 = tempI%10;
        tempI = tempI/10;
        tempDigit5 = tempI%10;
        tempI = tempI/10;
        tempDigit6 = tempI%10;
        if((tempDigit1+tempDigit2+tempDigit3) == (tempDigit4+tempDigit5+tempDigit6)){
            luckyCount++;
        }
                    //the number we are on is printed so we see the progress of the computing
        System.out.println("Lucky"+i);
    }
    System.out.println("Lucky Count = "+luckyCount);
}
    }

//In the end there is an output of 50412 so the last three digits of that is 412

#

Roy Tu
Dec 17, 2013

Haskell:

digits 0 = []
digits n = (digits (n `div` 10)) ++ [n `mod` 10]

isSixDigits = (==6) . length . digits
sumFirstThree n = sum $ take 3 $ digits n
sumLastThree n = sum $ take 3 $ reverse $ digits n

isLucky n = (isSixDigits n) && (sumFirstThree n == sumLastThree n)
run = reverse $ take 3 $ reverse $ digits $ length $ filter isLucky [100000..999999]
Neil Parikh
Dec 16, 2013

I mapped the numbers from 100,001 to 999,999 to a new array. If it is lucky, it will be replaced with a true, other wise with a false. Then I just count the number of trues in the array.

a = 100001.upto(999999).map do |n|
  str = n.to_s
  puts n if n % 100000 == 0
  str[0, 3].split("").map { |a| a.to_i }.reduce(:+) == str[3, 7].split("").map { |a| a.to_i }.reduce(:+)
end

puts a.count(true)
Manoj Pandey
Dec 16, 2013

Python Implementation:

def equal_digit_sums():

dists= {}

for i in range(1000):

    digits = [int(d) for d in str(i)]

    dsum = sum(digits)

    if dsum not in dists:

        dists[dsum] = [0,0]

    dists[dsum][0 if len(digits) == 3 else 1] += 1

def prod(dsum):

    t = dists[dsum]

    return (t[0]+t[1])*t[0]

return sum(prod(dsum) for dsum in dists)

print(equal_digit_sums())

Result: 50412 50412

Mateo Torres
Dec 16, 2013

I used C++:

int luckynumbers = 0;

for (int i = 100000; i < 1000000; i++)
{
if (((i / 100000) + ((i / 10000) % 10) + ((i / 1000) % 10)) == (((i / 100) % 10) + ((i % 100) / 10) + (i % 10)))
    {
                          luckynumbers++;
    }
}

cout << luckynumbers % 1000;

And got 412... I think the main problem was to obtain each digit from my int i... but it is actually easy to get the n number of an int; you should remember that to get any number from left to right, you should do a / 1 0 n a/10^n and if you wanted to get the number from right to left, you should do a p e r c e n t a g e 1 0 n a percentage 10^n . You can do this many times to break a string of integers.

Lokesh Sharma
Dec 15, 2013

Solution in Python:

res = 0
for i in range(100000, 1000000):
    i = str(i)
    i1, i2 = i[:3], i[3:]
    i1, i2 = map(int, i1), map(int, i2)
    if sum(i1) == sum(i2):
        res += 1
print res
Raj Magesh
Dec 14, 2013

I'm only an amateur programmer, so please give me suggestions on how to refine my code (in Python). Thanks!

def lucky(k):
    if int(str(k)[0]) + int(str(k)[1]) + int(str(k)[2]) == int(str(k)[3]) + int(str(k)[4]) + int(str(k)[5]):
        return True
    else:
        return False
count = 0
for k in range(100000, 1000000):
    if lucky(k):
        count += 1
print count

I got an output of 50412 in about 5 seconds.

That's about as optimized as you can get, I think. Something small: You should assign a variable to str(k) in the "lucky" function, so you don't have to convert it into a string each time.

Python is slower than most other languages, unfortunately :(

Michael Tang - 7 years, 5 months ago

Log in to reply

I got the answer in 1 ms using C++, I don't know much about Python but I'm sure you could have computed the answer in less time... you should check stackoverflow and Python documentation.

Mateo Torres - 7 years, 5 months ago

Mine takes 0.114000082016 seconds after adding one optimization, so maybe int and str are slow.

Daniel Chiu - 7 years, 5 months ago

This is what I did in Python:

def main():
    def sum_of_digits(n):
         count = 0
         for x in n:
             count += int(x)
         return count

    lucky_nums = 0

    for x in range(100000, 1000000):
        first3 = sum_of_digits(str(x)[:3])
        last3 = sum_of_digits(str(x)[3:])
        if first3 == last3:
            lucky_nums += 1
        print(str(lucky_nums)[2:])
main()

Sahibjot Saggu - 7 years, 5 months ago

I did a very similar thing:

h = 100000
x=0
while h<1000000:
  k=str(h)
  if int(k[0])+int(k[1])+int(k[2])==int(k[3])+int(k[4])+int(k[5]):
      x=x+1
   h=h+1
print x

Athmika Senthilkumar - 7 years, 5 months ago
Shubham Kumar
Dec 14, 2013

We can use the following C++ code:

include<constream.h>

void main()

{clrscr();

long n,count=0;

int a,b,r,s,c=0,d=0;

for(n=100000;n<=999999;n++)

{a= n/1000;

b= (n%1000);

while(a!=0)

{r=(a%10);

c= (c+r);

a=(a/10);

}

while(b!=0)

{s=(b%10);

d= (d+s);

b=(b/10);

}

if(c==d)

{cout<<"\t("<<c<<","<<d<<","<<n<<")";

count++;

}

c=0;

d=0;

}

cout<<"\n\tTotal = "<<count;

getch();

return;

}

Output: Total = 50412. Therefore, 412 (Ans)

You could wrap everything in a for-loop.

Mateo Torres - 7 years, 5 months ago

C solution: output 50412

int main() {

int i, j, a=0, b, p, q;

for (i=100000; i<=999999; i++)

{

b=0;

p=0;

q=0;

for (j=i; j>0; j=j/10)

{

if (b<3) p=p+j%10;

else if (b>=3) q=q+j%10;

b++;

}

if (p==q)

a++;

}

printf("%d", a);

}

Reaz Mahmud - 7 years, 4 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...