How to make powers of 9 quickly

2

I'm asking a question that asks to raise the number to 9 and say the last digit I got, but the resolution seems to have passed the time because it had a number of 10 ^ 9, how to solve it in a faster way My code

import  math
while True:
  try:
    numero = int(input())
    recebe = pow(9,numero)
    string = str(recebe)
    tam = len(string)
    print(string[tam-1])
except EOFError:
    break
    
asked by anonymous 23.05.2018 / 19:48

2 answers

2
  

asks to raise the number to 9

You say one thing and your code says another. When it does pow(9,numero) , it is raising 9 to a number , not a number to 9. Let's see things in two ways.

Last character, raising a given number to 9

Open a python file or prompt and paste the following:

for i in range(100):
    print(i, str(i**9)[-1])

What we are doing is showing a number from 0 to 99, and the last digit of that number when raised to 9.

You will find such a result:

75 5
76 6
77 7
78 8
79 9
80 0
81 1
82 2
83 3
...

Can you see any pattern there? The last digit of each number raised to 9 is the last digit of the number itself . It got easier, did not it? We can simplify the following code block:

numero = input()
print(numero[-1])

Last character, raising 9 to a given number

If the problem really is about raising 9 to a given number as in your code, we can try to find out if there is any other pattern.

for i in range(100):
    print(i, str(9**i)[-1])

Result:

56 1
57 9
58 1
59 9
60 1
61 9
62 1
...

Now, Batman. It seems we have another standard. For odd numbers the answer is 9 , and for pairs the answer is 1 . Our code looks like this:

numero = int(input())
print(1 if numero % 2 == 0 else 9)

Voila! We solved the problem without calculating a single power.

Moral of the story:

It may be worth studying the problem superficially before going straight into the solution.

    
24.05.2018 / 02:22
3

10 to the ninth power seems not to be the problem, the calculation is very fast.

I believe that pow is inverted, to raise a number to 9 would be the opposite, pow(9, numero) , the way you are doing 9 is elevated to N power.

Need this while true ? The only delay running on my computer would be this, because it goes back to the beginning and asks to type the number again.

    
23.05.2018 / 20:36