jbn6972

week9 prog assig1

Oct 9th, 2021 (edited)
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.99 KB | None | 0 0
  1. import sys
  2. import os
  3. import math
  4. if not os.environ.get("ONLINE_JUDGE"):
  5.     sys.stdin = open('./in.txt', 'r')
  6.     sys.stdout = open('./out.txt', 'w')
  7.  
  8. # rather than looping across all number max(a,b) we can use the foll. Euler's formula
  9. # gcd(a,b)=gcd(b,a%b) where b!=0
  10. # gcd(a,0)=a
  11.  
  12.  
  13. def gcd(a, b):
  14.     r = 0
  15.     while b != 0:
  16.         r = a % b
  17.         a = b
  18.         b = r
  19.     return a
  20.  
  21. # prime factors are the small possible units that can divide a number
  22.  
  23.  
  24. def prime_factor_count(n):
  25.     count = 0
  26.     # finding the number of twos that can divide n, as 2 is the only even prime numbe
  27.     while n % 2 == 0:
  28.         count += 1
  29.         n /= 2
  30.     # now that div by 2 is done, the n must be odd now
  31.     # and 1 is not prime, and 2 is covered, so we start at 3
  32.     i = 3
  33.  
  34.     # for any factors it is okay if we go only till sqrt(n)
  35.     while i < math.sqrt(n):
  36.         # check if n is divisible by i as many times as possible and update the count
  37.         # this is because we need the prime factors
  38.         # like 27=3*3*3
  39.         while n % i == 0:
  40.             count += 1
  41.             n /= i
  42.         i += 2
  43.  
  44.     # finally if any residue is present in n, it must be prime, beacuse we have divided by 2, and all other ints below sqrt(n), so we add that to the count too
  45.     if n > 2:
  46.         count += 1
  47.     return count
  48.  
  49.  
  50. n, m = map(int, input().split())
  51.  
  52. a = [0]
  53. a += list(map(int, input().split()))
  54.  
  55. pairs = []
  56. for _ in range(m):
  57.     pairs.append(list(map(int, input().split())))
  58. # print(pairs)
  59. # print(a)
  60.  
  61. div_count = 0
  62. for pair in pairs:
  63.     # find max number that can divide the pair
  64.     divisor = gcd(a[pair[0]], a[pair[1]])
  65.     # if n,m are coprime like gcd(5,9)=1, division by 1 is meaningless in our scenario, so omitting it
  66.     if divisor > 1:
  67.         # add the max number of times the pair can be divided
  68.         div_count += prime_factor_count(divisor)
  69.         # update the list value
  70.         a[pair[0]] /= divisor
  71.         a[pair[1]] /= divisor
  72. print(div_count)
  73.  
Add Comment
Please, Sign In to add comment