I have a homework assignment i Am totally confused on. I started with a basic code to determine if a number is prime or not, but need guidance from here. I will post assignment details then what I have so far.
Problem 1: Is it a prime number?
Write a Python program that allows the user to enter a whole number greater than 1 and that determines whether or not this number is a prime number. If it is a prime number, then
this information is simply printed. If it is not a prime number, then the list of factors (or divisor) of that number is returned. Here is a sample session of the program:
Please enter a number greater than 1 (0 for exit): 13757
13757 is a prime number!
Please enter a number greater than 1 (0 for exit): 10281
10281 is not a prime number.
It has the factors [3, 23, 69, 149, 447, 3427]
Please enter a number greater than 1 (0 for exit): 0
Thanks and good bye!
Approach: Your main program has a loop that asks the user for a number, as shown above. It exits if the user enters the number 0. The number input by the user is used to call a user-defined function get factors. For a number n, this function determines all factors of n and returns these factors as a list, which is then output in the main program. If the returned list is empty, then this means that n is a prime number. So you have to take care of these two cases (empty versus non-empty list) in your main program. Thus, the main algorithm of your program is realized in the function get factors. There are several ways to determine whether or not a given number is a prime number. You have to find an efficient way to determine all non-trivial factors of a number n in the function get factors. For “smart” (i.e.,
time efficient) solutions, we will give extra points!
Problem 2: How many prime numbers are there? (8 Points)
Write a Python program that asks the user for a number n and then writes all prime numbers less than or equal to n into a file called primes-n.txt. That is, the number n is part of the filename. Here is a sample session:
Please enter a number greater than 2: 50
Found 15 prime numbers; please check file primes-50.txt
For this example, the file primes-50.txt contains one prime number per line, e.g.,
2
3
5
7
11
13
17
....
41
43
47
HERE IS WHAT I HAVE SO FAR. JUST STARTED.
n = input ("Please enter a number greater than 1 (0 for exit):")
def isprime(n):
'''check if integer n is a prime'''
# range starts with 2 and only needs to go up the squareroot of n
for x in range(2, int(n**0.5)+1):
if n % x == 0:
return False
return True
print isprime(n)