📅  最后修改于: 2023-12-03 15:41:37.241000             🧑  作者: Mango
给定正整数N,求范围[1, N^2]中,有多少对正整数(i, j)满足 i*j = k^2 的形式。
对于任意正整数a和b,当且仅当a和b的素因子分解式中,每个素因子的幂次均为偶数时,a和b的积才是完全平方数。因此可将i和j分别进行素因子分解,并对各个素因子计算幂次的奇偶性,最终统计符合条件的i和j的数量即可。
def count_equal_pair(N):
factorization = [[] for _ in range(N+1)]
for i in range(2, N+1):
if not factorization[i]:
for j in range(i, N+1, i):
factorization[j].append(i)
cnt = [0] * (N+1)
for i in range(1, N+1):
for j in range(i, N+1):
product = i * j
if product > N*N:
break
odd_factors = []
even_fators = []
for factor in factorization[i]:
if product % (factor*factor) == 0:
even_fators.append(factor)
else:
odd_factors.append(factor)
for factor in factorization[j]:
if product % (factor*factor) == 0:
even_fators.append(factor)
else:
odd_factors.append(factor)
if len(set(odd_factors)) == 0:
cnt[product] += 1
elif len(set(odd_factors+even_fators)) == len(odd_factors) + len(even_fators):
cnt[product] += 1
return sum(cnt)
print(count_equal_pair(3)) # 2
print(count_equal_pair(4)) # 5
假设N为给定正整数,则该算法的时间复杂度为O(N^3/2logN),空间复杂度为O(NlogN)。其中,素因子分解的时间复杂度为O(NlogN),统计i*j=k^2的数量的时间复杂度为O(N^3/2logN)。空间复杂度需存储每个正整数的素因子分解结果。