how to determining whether a number is a perfect square number in Python

created at 06-30-2021 views: 3

question

The original question is this:

An integer, it is a perfect square number after adding 100 and adding 268. What is this number?

solution

After consulting some information, I finally used this sentence to judge:

len(str(math.sqrt(i)) > 5

The idea is: if a number is an integer after the root sign, then the length after it is converted into a string will not exceed 5 digits (provided that it is a number within 10000)
Determine if the number after the root sign (turned into a string) exceeds 5 digits, skip directly and calculate the next number

The complete code is as follows:

import math
for i in range(10000):
        if len(str(math.sqrt(i+100))) > 5 or len(str(math.sqrt(i+268))) > 5:
            continue
        else:
            print(i)

the output:

21
261
1581
Please log in to leave a comment.