How to make 9 potentials quickly

Asked

Viewed 408 times

1

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 number 10 9, how to solve it more quickly 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
  • No need to string or import math, you can calculate the module of 10 to get the last digit: https://repl.it/repls/MintyUnconsciousCopyright

  • hello miguel, even with this your idea my answer has not yet passed

  • what are the values and timeout you are working with? Click on the link in my comment above?

2 answers

5


asks to raise the number to 9

You say one thing and your code says another. When you do pow(9,numero), is bringing 9 to a number, and not a number at 9. Let’s look at 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’re doing is showing a number from 0 to 99, and the last digit of that number when raised to 9.

You’ll find a result like this:

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, didn’t it? We can simplify the next pro code block:

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

Last character, raising 9 to a given number

If the problem is really 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])

Upshot:

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

Well, Batman. We seem to have another pattern. For odd numbers the answer is 9, and to stop the answer is 1. Our code can stay like this:

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

Voilá! We solve the problem without calculating a single power.

Moral of the story: it may be worth studying the problem superficially before going to direct solution.

1

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

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

You 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.

  • The integer that will be raised to 9 is a number that 10 9

Browser other questions tagged

You are not signed in. Login or sign up in order to post.