2014-06-27 75 views
-1

嘿真棒蟒蛇人,Python:找到最大素數X

警告:我是新來的編碼。好吧,現在你已被警告......

我想寫一個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" 

的問題是在最後else語句的地方,其中x = 28和它的因素在處理數組時: [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變量,IA [],和n,使代碼更易讀

  • 在第二循環中,第一個循環之後,分析7時爲什麼代碼不認識到它是一個質數?

非常感謝任何建設性的反饋!

+0

我認爲這個問題更適合代碼審查。 http://codereview.stackexchange.com/ – shuttle87

+0

下面是一個通用的編程提示 - 儘可能明確地給你的變量命名,這樣你就可以確切知道它們是什麼以及它們應該發生什麼。 – MattDMo

+0

@MattDMo:不,這並不總是好的建議。 –

回答

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)) 

首先使用primes功能這是我從here了。它返回一個包含所有素數因子的數組。 然後,簡單地通過max-function,它給你數組中最大的元素。

輸出如下:

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

我希望這有助於。