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 ?
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.
All problems on Brilliant have a relatively small Python code it seems! :D
indent the code lines by 4 spaces
Log in to reply
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 |
|
Output: 5 0 4 1 2
Implying the answer to be: 4 1 2
Log in to reply
Why are you thanking me? :O
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.
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.
Done in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Loop through all possible values for each digit, only 9 ⋅ 1 0 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 |
|
gives 5 0 4 1 2 .
You could have made your code more efficient by running the loop for d in the range ( 0 , a + b + c + 1 ) , and the loop for e in the range ( 0 , a + b + c − d + 1 ) . Note that each valid selection of ( d , e ) corresponds to a unique f . Otherwise, that's how I did it. :)
Log in to reply
Well, that isn't always more efficient, as a + b + c + 1 could be greater than 10, and similarly for the other one. The f thing is a good idea.
Either way, efficiency wasn't needed, and I just tried to solve the problem as quickly as possible.
Log in to reply
Yeah, missed it! I guess we can define a function min which takes two numbers and returns their minimum, and run the loop from 0 to min ( 1 0 , 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).
Log in to reply
@Sreejato Bhattacharya – Well, I mean no optimization was necessary.
Also, I think min can be used after importing math.
How did you create that ash colored codish back??? I couldn't do it... :/
Log in to reply
Indent every line by four spaces.
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.
Excuse me. do you have a facebook account or an E-mail so i can contact with you ?
Great use of nested for loops to get the answer.
I did exactly same but in C++ :D
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:])
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 |
|
Cool! I did it exactly like that!
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);
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;
}
}
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);
The following code returns 5 0 4 1 2 .
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
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
1 2 3 4 5 6 |
|
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.
Python (somewhat efficient):
1 2 3 4 5 6 7 8 9 10 11 |
|
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;
}
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);
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
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
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:]))
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
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 4 1 2 .
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);
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 4 1 2
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)
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
#
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]
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)
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: 5 0 4 1 2
I used C++:
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++;
}
}
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 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 . You can do this many times to break a string of integers.
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
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 :(
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.
Mine takes 0.114000082016 seconds after adding one optimization, so maybe int and str are slow.
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()
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
We can use the following C++ code:
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.
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);
}
Problem Loading...
Note Loading...
Set Loading...
Here's a Python solution... Someone please show me how to create that ash colored codish background... :/
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