Python:找到X的最大素数

时间:2014-06-27 22:17:51

标签: python arrays naming-conventions

嘿,真棒的蟒蛇人,

警告:我不熟悉编码。好的,既然你被警告了......

我正在尝试编写一个python文件,找到我在代码中声明的变量的最大素数。

这是我的思考过程:

Step 1:Find Factors of X
Step 2:Put factors of X in an array a
Step 3:Analyze last element of array a
Step 4:Check if last element of array a is Prime
Step 5: if last element of array a is prime print "found the largest prime" along with the number itself, else, analyze second to last element in array a, and so on until at a[1]
Step 6: if no prime numbers in array, print "no primes found"

当处理x = 28及其在数组中的因素时,问题出现在最后一个else语句中的某处: [1,2,4,7,14]我的代码认为7不是素数......

我的步骤在线列出:

#find factors, put them in an array a

#1.Find factors of X
#2.Put factors of X in an array a

x=28
i=1
a=[]
length = 0

while i<x:      
    if x%i == 0:    #checks to see if X is divisible by anything between 1 and X-1
        a.append(i)  #adds factor to array a
    i = i+1         

print "your factors are: ", "\n", a
print "\n"


#3. Analyze the last element in array a
# Before loop below, a = [1, 2, 4, 7, 14] and length = 5

length = 0
length = len(a)
n=a[length-1]-1  
print "checking for primes in your array now...", "\n"

while len(a) > 2:
    if a[length-1]%n != 0:       
        n=n-1
        if n == 1:
            print "PRIME TIME"
            break
    else:
        print a[length-1], "is not a prime"  #added
        del a[-1]
        length = len(a) 
        print "length = ",length
        if length == 2:
            print "NO Primes"

几个问题:

  • 您如何重新分配x,i a []和n等变量以使代码更具可读性

  • 在第二次循环中,在第一次迭代之后,当分析7为什么代码不能识别它是素数?

非常感谢任何建设性的反馈!!

1 个答案:

答案 0 :(得分:2)

好的,我会这样做:

def primes(n):
    primfac = []
    d = 2
    while d*d <= n:
        while (n % d) == 0:
            primfac.append(d)  
            n /= d
        d += 1
    if n > 1:
       primfac.append(n)
    return primfac

print "Factors: ", primes(28)
print "The largest is: ", max(primes(28))

首先使用我从here获取的primes函数。它返回一个包含所有素因子的数组。 然后,简单地使用max-function,它将为您提供数组中最大的元素。

输出如下:

Factors:  [2, 2, 7]
The largest is:  7

我希望这会有所帮助。