python-3.xfactorssquare-root

python perfect square free numbers and its factors


I want to get the numbers which are not perfect square and are the factors of the input number the problem I'm facing here is suppose we give a input of 72 so 36 is the perfect square but 12 is not, but in factors of 12 4 is a perfect square so 12 cannot be counted now I want to get the numbers who are free of perfect square and the free of perfect square factors also so in 72 only 2,3 and 6 are perfect square free number

I am trying the approach is to find the factors then if the factors arent perfect square then its added to another list then I want to again get their factors and if there's no perfect square in it add them into another list and print it out I got the non perfect square factors but I am not able to find the logic of next step i.e getting their factors and eliminating who have factors as perfect square

def is_square(apositiveint):
    x = apositiveint // 2
    seen = set([x])
    while x * x != apositiveint:
        x = (x + (apositiveint // x)) // 2
        if x in seen:
            return False
        seen.add(x)
    return True


def print_factors(x):

    _list = []
    _list_1 = []
    _list_2 = []

    print("The factors of", x, "are:")
    for i in range(2, x + 1):
        if x % i == 0:
            if is_square(i) == False:
                _list.append(i)
            else:
                _list_1.append(i)
    return _list


num = int(input("Enter the number"))

_list_1 = []

_list_1 = print_factors(num)

number = []

for x in range(0, len(_list_1)):
    number = print_factors(_list_1[x])
    print(number)

input

72

output

The factors of 72 are: The factors of 2 are: [2] The factors of 3 are: [3] The factors of 6 are: [2, 3, 6] The factors of 8 are: [2, 8] The factors of 12 are: [2, 3, 6, 12] The factors of 18 are: [2, 3, 6, 18] The factors of 24 are: [2, 3, 6, 8, 12, 24] The factors of 72 are: [2, 3, 6, 8, 12, 18, 24, 72]


Solution

  • You can tackle the same problem in a different way:

    1. Write a function that computes the factors of t=the number.factors(x)

    2. Write another fucnction that determines whether a number or its factors are perfect squares: perfc_sqr(x)

    3. Lastly write a function that returns perfect square free factors:

      import numpy as np
      def factors(x):
          nums =  np.arange(2,x+1)
          return nums[x % nums == 0]
      
      def perfc_sqr(x):
          pnum = np.sqrt(factors(x))[1:]
          return any(pnum== np.array(pnum,dtype="i"))
      
      def perfect_square_free(x):   
          return [i for i in factors(x) if not perfc_sqr(i)]
      perfect_square_free(72)
      [2, 3, 6]