Numbers can be special

A number is said to be special if the sum of the squares of its digits on even places is equal to the sum of the squares of its digits on odd places.

For example,
354 354 is a special number, because 3 2 + 4 2 = 5 2 = 25 3^{2} + 4^{2} = 5^{2} = 25 .
1784 1784 is a special number, because 1 2 + 8 2 = 7 2 + 4 2 = 65 1^{2} + 8^{2} = 7^{2} + 4^{2} = 65 .

Let f ( n ) f(n) be a function that counts the number of special numbers less than or equal to n, and g ( n ) g(n) be a function that finds the sum of special numbers less than or equal to n n . Find g ( f ( f ( 1 0 6 ) ) ) g(f(f(10^{6}))) .


The answer is 605.

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.

2 solutions

Soumava Pal
Mar 20, 2016
 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
>>> def special(n):
        m=n
        c=0
            p=0
        while m>0:
                d=m%10
                c+=1
                if c%2==1: p+=d*d 
                else: p-=d*d
                m/=10
         if p==0: return 1
         return 0

>>> def f(n):
         c=0
         for i in range(1,n+1):
            if special(i)==1:
                c+=1
         return c

>>> def g(n):
         c=0
         for i in range(1,n+1):
            if special(i)==1:
                c+=i
         return c

>>> g(f(f(10**6)))
605
>>> 

Python:

def isspecial(n):
    a = str(n)
    if sum(int(x)**2 for x in a[::2])==sum(int(x)**2 for x in a[1::2]):
        return True
    else:
        return False

def f(n):
    return sum(1 for i in range(1,n+1) if isspecial(i))
def g(n):
    return sum(i for i in range(1,n+1) if isspecial(i))

A Former Brilliant Member - 5 years, 1 month ago

I feel a little functional today. This might be slower though, but tight cute code.

Python 3

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
def specialQ(n):
    n = str(n)
    odd, even = 0,0
    for i in range(0,len(n)):
        if i%2:
            odd += int(n[i])**2
        else:
            even += int(n[i])**2
    return odd == even

f = lambda n: len(list(filter(specialQ,range(1,n+1))))
g = lambda n: sum(filter(specialQ,range(1,n+1)))

Finally, run

1
2
>>> g(f(f(1000000)))
605

4 lines for everything.

Python 3, 196 characters (204 bytes)

1
2
3
4
special=lambda n: sum((-1)**i*int(n[i])**2 for i in range(len(n)))==0
f=lambda n: sum(special(str(i)) for i in range(n+1))
g=lambda n: sum(i*special(str(i)) for i in range(n+1))
print(g(f(f(10**6))))

A bit slower than your code though.

Prasun Biswas - 5 years, 2 months ago

Log in to reply

Yeah, this is cool too

Agnishom Chattopadhyay - 5 years, 2 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...