Created
July 9, 2013 09:14
-
-
Save ajaykgp/5955906 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This function solves the problem no. 40 of project-euler | |
# The link to the problem: http://projecteuler.net/problem=40 | |
# We find a correspondence in the two below sequences s1 and s2: | |
# s1 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2, 1, 3, ... | |
# s2 = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ... | |
# the function nth_digit(n) finds the nth term of s1 | |
# termcount is the term of s2 in which nth term of s1 lies at position numdigit | |
# from the left | |
import math | |
def digit(n, t): | |
for i in range(t - 1): | |
n /= 10 | |
return n % 10 | |
def nth_digit(n): | |
numlen = 1 | |
termcount = 0 | |
numdigit = 0 | |
while n > 0: | |
temp = int(numlen * 9 * math.pow(10, numlen - 1)) | |
if n - temp >= 0: | |
n -= temp | |
termcount += int(9 * math.pow(10, numlen - 1)) | |
numlen += 1 | |
else: | |
numnum = n / numlen | |
numdigit = n % numlen | |
termcount += numnum if numdigit == 0 else numnum + 1 | |
break | |
if numdigit == 0: | |
return termcount % 10 | |
else: | |
return digit(termcount, numlen - numdigit + 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment