Tuesday, 15 January 2013

python - How many inverse numbers equal only odd numbers under 1 billion -



python - How many inverse numbers equal only odd numbers under 1 billion -

i trying write script allow me come value below.

when integers greater 0 summed transposed value [x + transpose(x)] result number consisting of odd digits. example:

54 + 45 = 99 605 + 506 = 1111

we phone call these numbers flip-flops; 45, 54, 506, , 605 flip-flops. zeroes not acceptable leading digits in either x or tran‍‍spose(x)‍‍‍‍. how many flip-flop numbers there below 1 billion (10^9)?

i'm thinking of way in pseudo-code:

if [x+transpose(x)] = odd numbers flipflop = true how many flipflops <1,000,000,000

i'm struggling syntax however. can help? i'm trying in python

since takes odd plus number create odd number, need odd , number create flipflop. limits number of candidates need test find flipflops < 10**9.

furthermore, since flipflop pairs composed of odd , number, 1 of numbers must begin odd number , other must begin number.

therefore, number in flipflop must of form

[odd_digits] + [zero_to_nine]*(ndigits-2) + [even_digits]

in other words, begins odd digit, ends digit, , can digit in middle.

the final even_digit can not 0 since odd flipflop can not begin zero.

you need generate candidate numbers of above form, since when reverse digits candidate odd numbers. more count same flipflops twice.

a farther optimization speed utilize integers only. no strings. generally, converting between ints , strings takes more time arithmetic computations.

import itertools zero_to_nine = range(10) even_digits = [2, 4, 6, 8] odd_digits = [1, 3, 5, 7, 9] flipflops = 0 ndigits in range(2, 10): digits in it.product(*( [odd_digits] + [zero_to_nine]*(ndigits-2) + [even_digits])): reversed_digits = digits[::-1] carry = 0 # print('testing {!r}'.format(digits)) a, z in zip(digits, reversed_digits): total = a+z+carry # print('total: {}'.format(total)) if total % 2 == 0: break else: carry = total//10 else: # print('{!r} + {!r}'.format(digits, reversed_digits)) flipflops += 1 print(flipflops)

yields

304360

in 6 minutes.

python math

No comments:

Post a Comment