Suppose we have a number n, we have to find out the probability that any proper divisor of n would be an even perfect square.
So, if the input is like n = 36, then the output will be 1/8 because there are eight proper divisors of 36, these are {1,2,3,4,6,9,12,18} and among them only one number (4) is perfect square and even.
To solve this, we will follow these steps −
- if n mod 4 is not same as 0, then
- return 0
- otherwise,
- nc := n, ptr := 2
- l := a new list
- while ptr <= square root of nc , do
- a := 0
- while nc mod ptr is same as 0, do
- a := a + 1
- nc := floor of (nc / ptr)
- if a > 0, then
- append a into the list l
- ptr := ptr + 1
- if nc > 1, then append 1 into the list l
- k := l[0]
- d := k + 1
- no := floor of (k / 2)
- for each i in l[from index 1 to end], do
- d := d *(i + 1)
- no := no * floor of (i / 2) + 1
- d := d - 1
- if n is a perfect square, then
- no := no - 1
- g := gcd of d and no
- d := floor of d / g
- no := floor of no / g
- if no is same as 0, then
- return 0
- otherwise,
- return a fraction no/d
Example
Let us see the following implementation to get better understanding −
from math import gcd def solve(n): if n % 4 != 0: return 0 else: nc = n ptr = 2 l = [] while ptr <= nc ** 0.5: a = 0 while nc % ptr == 0: a += 1 nc = nc / ptr if a > 0: l += [a] ptr += 1 if nc > 1: l += [1] k = l[0] d = k + 1 no = int(k / 2) for i in l[1:]: d = d * (i + 1) no *= int(i / 2) + 1 d = d - 1 if int(n ** 0.5) ** 2 == n: no -= 1 g = gcd(d, no) d = d // g no = no // g if no == 0: return 0 else: return str(no) + '/' + str(d) n = 36 print(solve(n))
Input
4, 27
Output
1/8