Hey awesome python people,
Warning: I am new to coding. Ok, now that you have been warned...
I am trying to write a python file that finds the largest prime number of a variable I declare inside the code.
Here is my thought process:
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"
The issue is somewhere in the last else statement, when dealing with x=28 and its factors in an array: [1, 2, 4, 7, 14] my code thinks 7 is not a prime...
My steps are listed in-line:
#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"
A few questions:
How would you re-assign variables like x, i a[], and n to make the code more readable
In the second loop, after the first iteration, when analyzing 7 why does the code not recognize that it is a prime number?
Thanks so much for any constructive feedback!!