I'm a returning college student in a Python class and I'm STUCK. I promise I'll post a proper intro later, and forgive me if this topic's been beaten to death, but I'm up to my neck and don't have a lot of time. I've got a HW assignment to 1)write a Python program that determines if a given number is prime and then 2) embed the code as a function to find all primes <= n. I've got a working prime-finder, but I can't figure out how to set it up as a function to check all values <n. First, here's my functional prime-detector:
def main():
n = input("Enter a number:")
prime = True
for d in range(3,int(n**0.5)+1,2):
if n%d==0:
prime=False
elif n%2==0:
prime = False
if prime==False:
print int(n)," is not prime"
else:
print int(n), "is prime"
main()
This is how I have it as a function; it works, but i can't figure out how to attach the range-finder:
def testfun(n):
prime = True
for d in range(3,int(n**0.5)+1,2):
if n%d==0 or n%2==0:
prime = False
if prime==False:
pass
else:
print int(n),
def main():
n = input("Enter a number:")
testfun(n)
main()
and here's a range-finder I wrote that returns "false positives", i.e. odd composites (21, etc.) as prime:
def findprimes(n):
prime=True
for n in range(2,n+1):
n*=1.0
if n/2==int(n/2)and n!=2:
prime = False
for d in range(2,8):
if n%d==0:
prime=False
if prime==False:
pass
else:
print int(n),
def main():
print "This program finds all primes"
print "up to any value 'n'."
n = input ("enter a number greater than 1:")
findprimes(n)
main()
I hope this isn't overload for my first post, and thanks for any light you can shed.

New Topic/Question
Reply



MultiQuote






|