Veronica T
Veronica T

Reputation: 23

Unable to code for non-squares integers in Python

How do I create a code that prints out all the integers less than 100 that are not a square of any integer?

For instance, 3^2=9 to not be printed, but 30 should.

I’ve managed to print out the squared values but not sure how to print out the values that are not a square.

Here is my code:

for i in range(1,100):
    square = i**2

    print(square)

Upvotes: 1

Views: 304

Answers (2)

Shayan Shafiq
Shayan Shafiq

Reputation: 1469

There can be multiple ways you can write this code. I think you can use two for loops here to make it easier for you. I'm using comments so for you being a newbie to understand better. You can choose from these two whichever you find easier to understand:

list_of_squares = []               #list to store the squares
              
for i in range(1, 11):             #since we know 10's square is 100 and we only need numbers less than that
    square = i ** 2
    list_of_squares.append(square) #'append' keeps adding each number's square to this list
    
for i in range(1, 100):
    if i not in list_of_squares:   #'not in' selects only those numbers that are not in the squares' list
        print(i)

Or

list_of_squares = []

for i in range(1, 100):
    square = i ** 2
    list_of_squares.append(square)
    if square >= 100:              #since we only need numbers less than 100
        break                      #'break' breaks the loop when square reaches a value greater than or equal to 100
        
for i in range(1, 100):
    if i not in list_of_squares:
        print(i)

Upvotes: 2

苏小刚
苏小刚

Reputation: 36

You can store the nums that is square of integers into a array.

squares =[]
for i in range(1,100):
    squares.append(i**2)

j = 0
for k in range(1,100):
    if k==squares[j]:
        j=j+1
    elif k>squares[j]:
        print(k)
        j=j+1
    else:
        print(k)

Upvotes: 1

Related Questions