arrays - Python: find the largest prime number of X -
hey awesome python people,
warning: new coding. ok, have been warned...
i trying write python file finds largest prime number of variable declare inside code.
here thought process:
step 1:find factors of x step 2:put factors of x in array step 3:analyze last element of array step 4:check if last element of array prime step 5: if last element of array prime print "found largest prime" along number itself, else, analyze second last element in array a, , on until @ a[1] step 6: if no prime numbers in array, print "no primes found" the issue somewhere in last else statement, when dealing x=28 , factors in array: [1, 2, 4, 7, 14] code thinks 7 not prime...
my steps listed in-line:
#find factors, put them in array #1.find factors of x #2.put factors of x in array x=28 i=1 a=[] length = 0 while i<x: if x%i == 0: #checks see if x divisible between 1 , x-1 a.append(i) #adds factor array = i+1 print "your factors are: ", "\n", print "\n" #3. analyze last element in array # before loop below, = [1, 2, 4, 7, 14] , length = 5 length = 0 length = len(a) n=a[length-1]-1 print "checking primes in 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 prime" #added del a[-1] length = len(a) print "length = ",length if length == 2: print "no primes" a few questions:
how re-assign variables x, a[], , n make code more readable
in second loop, after first iteration, when analyzing 7 why code not recognize prime number?
thanks constructive feedback!!
ok, this:
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)) first use primes function took here. returns array containing prime factors. then, aply max-function, gives largest element of array.
the output follows:
factors: [2, 2, 7] largest is: 7 i hope helps.
Comments
Post a Comment