-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時爲什麼代碼不認識到它是一個質數?
非常感謝任何建設性的反饋!
我認爲這個問題更適合代碼審查。 http://codereview.stackexchange.com/ – shuttle87
下面是一個通用的編程提示 - 儘可能明確地給你的變量命名,這樣你就可以確切知道它們是什麼以及它們應該發生什麼。 – MattDMo
@MattDMo:不,這並不總是好的建議。 –