-1

I had a Codility Test, and the question asked me to create a code that listed numbers 1-1000, but at every square number, the program prints "POWER" instead of the square number. It should look like this:

POWER
2
3
POWER
5
6
7
8
POWER
10

And so on... I've been trying to solve this, but I can't think of any correct solutions, any help would be much appreciated.

for n in range(1,11):
    print(n)
    if n == n**2:
        print("POWER")
    elif n==22:
        print("POWER")
    elif n==3**2:
        print("POWER")

This is the only thing I could think of, but I don't know how I could create a loop for this 1000 times, also the output didn't come out as I wanted it to.

Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32

2 Answers2

1

My solution is: calculate sqrt of number, check if it is a whole number using built-in method is_integer() on float object:

import math
for i in range(1000):
    if math.sqrt(i).is_integer():
        print("POWER")
    else:
        print(i)
0

The important things you're missing are the math.sqrt and round functions, which make it very easy to figure out if a number is a perfect square (just check whether the sqrt of the number is round):

import math

for n in range(1,1001):
    s = math.sqrt(n)
    if s == round(s):
        print("POWER")
    else:
        print(n)

If you weren't allowed to use those functions, another option (which would save you from having to do a guess-and-test iteration for each number) would be to build a set of square numbers within the range you care about and test each n for membership in that set:

squares = {n ** 2 for n in range(1, 32)}
for n in range(1,1001):
    if n in squares:
        print("POWER")
    else:
        print(n)
Samwise
  • 68,105
  • 3
  • 30
  • 44