[Tutor] Root and power

Steven D'Aprano steve at pearwood.info
Wed Jul 29 17:08:53 CEST 2015


On Tue, Jul 28, 2015 at 08:29:00PM -0700, Job Hernandez wrote:
[...]
>  I need to learn how in the world do find the root and power of an integer
> that x user entered? I haven been looking on the python website for an
> appropriate function but I have not.

Let's suppose the user entered 36. Then the possible answers are:

36**1 = 36
6**2 = 36

and I think that's about it. We know that pwr=0 won't give any solutions 
unless the number itself is 1:

1**0 = 1
2**0 = 1
3**0 = 1
4**0 = 1

etc. So if the user enters 1, you can just print root=1 and pwr=0 and 
you are done. (For that matter, you could print any value for root!)

Otherwise, for any pwr other than 1, we want to find some root such 
that:

root**pwr = the number the user entered

How might we do this for, say, pwr=2, and the number 25? There's no 
built in function for this, instead you need to do a loop, testing each 
number in turn:

1**2 = 1, too small
2**2 = 4, too small
3**2 = 9, too small
4**2 = 16, too small
5**2 = 25, equals the user's number

so this tells us that 25 is a perfect square, and we can now print 
root=5, pwr=2.

How about pwr=2, number = 27?

1**2 = 1, too small
2**2 = 4, too small
3**2 = 9, too small
4**2 = 16, too small
5**2 = 25, too small
6**2 = 36, too big

So this tells us that 27 is NOT a perfect square. Let's check to see if 
it's a perfect cube:

1**3 = 1, too small
2**3 = 8, too small
3**3 = 27, equals the user's number

so 27 is a perfect cube, and we can print root=3, pwr=3.

Obviously we don't actually need to check root=1, since 1 to the power 
of anything is always 1. Let's try (say) 59:

2**2 = 4, too small
3**2 = 9, too small
...
7**2 = 49, too small
8**2 = 64, too big -- pwr cannot be 2
2**3 = 8, too small
3**3 = 27, too small
4**3 = 64, too big -- pwr cannot be 3
2**4 = 16, too small
3**4 = 81, too big -- pwr cannot be 4
2**5 = 32, too small
3**5 = 243, too big -- pwr cannot be 5
2**6 = 64, too big -- pwr cannot be 6

At this point you have a choice:

print "No such root and pwr"

print "root=59, pwr=1"

but I guess the second one is probably going against the spirit of the 
question. Or maybe not? Hard to say.


Obviously you shouldn't write out all the tests by hand:

# No, don't do this!
if 2**2 == number:
    print("root=2, pwr=2")
elif 3**2 == number:
    print("root=3, pwr=2")
elif 4**2 == number:
    print("you've got to be kidding, I quit!")


Instead you will use for-loops and range, and break to exit out of the 
loop early.

for pwr in range(2, 7):
    for root in range(2, num):
        ...


Is that enough of a hint, or do you need more assistence?



-- 
Steve


More information about the Tutor mailing list