给定多个范围[L,R]和质数p,我们需要找到给定单个范围内的所有P平滑数。
What is P – smooth number?
An integer is P – smooth number if the largest Prime factor of that number <= p. 1 is considered (by OEIS) as P – smooth number for any possible value of P because it does not have any prime factor.
例子:
Input : p = 7
ranges[] = {[1, 17], [10, 25]}
Output :
For first range : 1 2 3 4 5 6 7 8 9 12 14 15 16
For second range : 15 16 18 20 21 24 25
Explanation : Largest prime factors of numbers
printed above are less than or equal to 7.
假设我们正在检查7 –平滑数字。
1.考虑一个整数56。这里56 = 2 * 2 * 2 * 7。
因此,56具有两个主因子(2和7),这些主因子<= 7。因此,56是7平滑数字。
2.考虑另一个整数66。这里66 = 2 * 3 * 11。
66具有三个主要因子(2、3和11)。其中11> 7。所以66不是7平滑数字。
蛮力法:给出P和范围[L,R]。在这里L <=R。创建一个循环并检查所有包含[L:R]的数字。如果该数字的最大素数<= p。然后打印该号码(即P平滑号码)。使用maxPrimeDivisor(n)函数计算其最大素数/除数。高效方法:想法是预先计算p平滑数以获取所有范围的最大值。一旦我们进行了预先计算,我们就可以一张一张地快速打印所有范围。
# Python program to display p-smooth
# number in given range.
# P-smooth numbers' array
p_smooth = [1]
def maxPrimeDivisor(n):
# Returns Maximum Prime
# Divisor of n
MPD = -1
if n == 1 :
return 1
while n % 2 == 0:
MPD = 2
n = n // 2
# math.sqrt(n) + 1
size = int(n ** 0.5) + 1
for odd in range( 3, size, 2 ):
while n % odd == 0:
# Make sure no multiples
# of prime, enters here
MPD = odd
n = n // odd
# When n is prime itself
MPD = max (n, MPD)
return MPD
def generate_p_smooth(p, MAX_LIMIT):
# generates p-smooth numbers.
global p_smooth
for i in range(2, MAX_LIMIT + 1):
if maxPrimeDivisor(i) <= p:
# Satisfies the condition
# of p-smooth number
p_smooth.append(i)
def find_p_smooth(L, R):
# finds p-smooth number in the
# given [L:R] range.
global p_smooth
if L <= p_smooth[-1]:
# If user input exceeds MAX_LIMIT
# range, no checking
for w in p_smooth :
if w > R : break
if w >= L and w <= R :
# Print P-smooth numbers
# within range : L to R.
print(w, end =" ")
print()
# p_smooth number : p = 7
# L <= R
p = 7
L, R = 1, 100
# Maximum possible value of R
MAX_LIMIT = 1000
# generate the p-smooth numbers
generate_p_smooth(p, MAX_LIMIT)
# Find an print the p-smooth numbers
find_p_smooth(L, R)