Euler Problem 206 – Don’t be such a square!


Check out the wikipedia article on square numbers (the numbers article, not the algebra one).
A couple few interesting properties emerge that can be exploited.

http://en.wikipedia.org/wiki/Square_number

1) A square number can end only with digits 00,1,4,6,9, or 25 in base 10; So that eliminates 2 digits, we now end with a 9.
2) Squares of odd numbers are odd.
3) If the last digit of a number is 3 or 7, its square ends in 9.

and if, and if, and if … you get the idea.

PS. I could have used the divisible by 4 rule also here, but I didn’t need to. This routine still runs in under a minute without importing psyco.

class Problem:
    def test (self, n):
        N = str(n*n)
        if N[0] == '1':
            if N[2] == '2':
                if N[4] == '3':
                    if N[6] == '4':
                        if N[8] == '5':
                            if N[10] == '6':
                                if N[12] == '7':
                                    if N[14] == '8':
                                        if N[16] == '9':
                                            return True
        return False
    def Solution(self):
        number = 0
        start = int(math.floor(math.sqrt(10203040506070809)))
        end = int(math.floor(math.sqrt(19293949596979899)))
        for i in range (start,end):
            if i % 2 != 0:
                if int(str(i)[-1]) == 3 or int(str(i)[-1]) == 7:
                    if self.test(i) == True:
                        number = int(math.sqrt(int(str(i*i)+"00")))
                        break
        print "Answer =", number
if __name__ == '__main__':
    P = Problem()
    P.Solution()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s