473,404 Members | 2,195 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

Prime Numbers

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.

Expand|Select|Wrap|Line Numbers
  1. n = input ("Please enter a number greater than 1 (0 for exit):")
  2.  
  3. def isprime(n):
  4.     '''check if integer n is a prime'''
  5.     # range starts with 2 and only needs to go up the squareroot of n
  6.     for x in range(2, int(n**0.5)+1):
  7.         if n % x == 0:
  8.             return False
  9.     return True
  10.  
  11. print isprime(n)
Mar 3 '08 #1
12 6175
bvdet
2,851 Expert Mod 2GB
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.

Expand|Select|Wrap|Line Numbers
  1. n = input ("Please enter a number greater than 1 (0 for exit):")
  2.  
  3. def isprime(n):
  4.     '''check if integer n is a prime'''
  5.     # range starts with 2 and only needs to go up the squareroot of n
  6.     for x in range(2, int(n**0.5)+1):
  7.         if n % x == 0:
  8.             return False
  9.     return True
  10.  
  11. print isprime(n)
That is a good start. To compile a list of factors, you can create a function similar to isprime(). Create an empty list. You will need to set the range upper limit to (n/2)+1. If n % x returns 0, append n to the list. The function should return the list.
Mar 3 '08 #2
Having trouble still with listing the factors if it is not a prime number. Any advice would be great. Here's what I got.
Expand|Select|Wrap|Line Numbers
  1. n = input ("Please enter a number greater than 1 (0 for exit):")
  2.  
  3. def isprime(n):
  4.     '''check if integer n is a prime'''
  5.     # range starts with 2 and only needs to go up the squareroot of n
  6.     for x in range(2, int(n**0.5)+1):
  7.         if n % x == 0:
  8.             return False
  9.     return True
  10.  
  11.  
  12.  
  13.  
  14. if isprime(n) is True:
  15.                print n, "is a prime number!"
  16. if isprime(n) is False:
  17.                 print n, "is not a prime number" 
  18. print isprime(n)
Mar 4 '08 #3
Laharl
849 Expert 512MB
Python's true and false values are 'True' and 'False', which are case-sensitive. Thus, regardless of your isprime code, you'll get errors there.
Mar 4 '08 #4
bvdet
2,851 Expert Mod 2GB
Having trouble still with listing the factors if it is not a prime number. Any advice would be great. Here's what I got.
Expand|Select|Wrap|Line Numbers
  1. n = input ("Please enter a number greater than 1 (0 for exit):")
  2.  
  3. def isprime(n):
  4.     '''check if integer n is a prime'''
  5.     # range starts with 2 and only needs to go up the squareroot of n
  6.     for x in range(2, int(n**0.5)+1):
  7.         if n % x == 0:
  8.             return False
  9.     return True
  10.  
  11.  
  12.  
  13.  
  14. if isprime(n) is True:
  15.                print n, "is a prime number!"
  16. if isprime(n) is False:
  17.                 print n, "is not a prime number" 
  18. print isprime(n)
The code is correct, but you seem to have an indentation problem. There is no need to check if the value returned by the function is True or False.
Expand|Select|Wrap|Line Numbers
  1. if isprime(n):
  2.     print n, "is a prime number!"
  3. else:
  4.     print n, "is not a prime number" 
  5. print isprime(n)
Mar 4 '08 #5
Ok. Getting close to the end. 2 questions.
1. Still have problem listing factors if number is not prime, in part 1 of assignment.
2. How do I output p to a string so I can output p to a file? It is towards end of code.
3. Which code do i use to exit the program if the user enters 0?
Here is what I got.
Expand|Select|Wrap|Line Numbers
  1. n = input ("Please enter a number greater than 1 (0 for exit):")
  2.  
  3. def isprime(n):
  4.     '''check if integer n is a prime'''
  5.     # range starts with 2 and only needs to go up the squareroot of n
  6.     for x in range(2, int(n**0.5)+1):
  7.         if n % x == 0:
  8.             return False
  9.     return True
  10. if isprime(n):
  11.     print n, "is a prime number!"
  12. else:
  13.     print n, "is not a prime number"
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27. n = input ("Please enter a number greater than 2: ")
  28. outfile = 'primes-'+str(n)+'.txt'
  29. output = open (outfile, "w")
  30. def get_factors(n):
  31.     List1 = []
  32.     List2 = []
  33.     List3 = []
  34.     for x in range(2, int(n**0.5)+1):
  35.         if n % x == 0:
  36.             List1 = List1 + [x]
  37.             for y in List1:
  38.                 c = n / y
  39.                 if c not in List2:  
  40.                     List2 = List2 + [c]
  41.     List3 = List1 + List2
  42.     List3.sort()
  43.     return List3
  44. def prime_number(n):
  45.     List4 = []
  46.     for n in range(2, n+1):
  47.         if get_factors(n) == []:
  48.             List4 = List4 + [n]
  49.     return List4
  50.  
  51. p = prime_number(n)
  52. output.write(p)
  53. print "Found", len(prime_number(n)), "numbers; please check file primes-",n,".txt"
  54.  
Mar 4 '08 #6
bvdet
2,851 Expert Mod 2GB
Ok. Getting close to the end. 2 questions.
1. Still have problem listing factors if number is not prime, in part 1 of assignment.
2. How do I output p to a string so I can output p to a file? It is towards end of code.
3. Which code do i use to exit the program if the user enters 0?
Here is what I got.
Expand|Select|Wrap|Line Numbers
  1. n = input ("Please enter a number greater than 1 (0 for exit):")
  2.  
  3. def isprime(n):
  4.     '''check if integer n is a prime'''
  5.     # range starts with 2 and only needs to go up the squareroot of n
  6.     for x in range(2, int(n**0.5)+1):
  7.         if n % x == 0:
  8.             return False
  9.     return True
  10. if isprime(n):
  11.     print n, "is a prime number!"
  12. else:
  13.     print n, "is not a prime number"
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27. n = input ("Please enter a number greater than 2: ")
  28. outfile = 'primes-'+str(n)+'.txt'
  29. output = open (outfile, "w")
  30. def get_factors(n):
  31.     List1 = []
  32.     List2 = []
  33.     List3 = []
  34.     for x in range(2, int(n**0.5)+1):
  35.         if n % x == 0:
  36.             List1 = List1 + [x]
  37.             for y in List1:
  38.                 c = n / y
  39.                 if c not in List2:  
  40.                     List2 = List2 + [c]
  41.     List3 = List1 + List2
  42.     List3.sort()
  43.     return List3
  44. def prime_number(n):
  45.     List4 = []
  46.     for n in range(2, n+1):
  47.         if get_factors(n) == []:
  48.             List4 = List4 + [n]
  49.     return List4
  50.  
  51. p = prime_number(n)
  52. output.write(p)
  53. print "Found", len(prime_number(n)), "numbers; please check file primes-",n,".txt"
  54.  
There is a simpler way to get a list of factors. You don't need function prime_number. Iterate on range(2, (number/2)+1).
Expand|Select|Wrap|Line Numbers
  1. >>> factorlist = [i for i in range(2, int(297/2.0)+1) if not 297%i]
  2. >>> factorlist
  3. [3, 9, 11, 27, 33, 99]
  4. >>> factorlist = [i for i in range(2, int(97/2.0)+1) if not 97%i]
  5. >>> factorlist
  6. []
  7. >>> 
Skip the function call if the number is 0 with an if statement.
Expand|Select|Wrap|Line Numbers
  1. >>> n = 0
  2. >>> if n > 1:
  3. ...     print "Proceed"
  4. ... else:
  5. ...     print "Exit"
  6. ...     
  7. Exit
  8. >>> 
HTH
Mar 4 '08 #7
I appreciate your help so much. I swear these are my last questions. I am almost completely done. I just have 2 problems.
1. I still cant get the program to stay in the first part UNLESS the user inputs 0, then it should move on to the second part of the program.
2. Still having problems writing results of part 2 of assignment to a file. I think i need to make results into a string then write to a file.
Mar 6 '08 #8
bvdet
2,851 Expert Mod 2GB
I appreciate your help so much. I swear these are my last questions. I am almost completely done. I just have 2 problems.
1. I still cant get the program to stay in the first part UNLESS the user inputs 0, then it should move on to the second part of the program.
2. Still having problems writing results of part 2 of assignment to a file. I think i need to make results into a string then write to a file.
Try something like this:
Expand|Select|Wrap|Line Numbers
  1. def part_one():
  2.     while True:
  3.         num = int(raw_input("Enter a positive number or 0 to exit."))
  4.         if num > 0:
  5.             ....call your prime number function here....
  6.         else:
  7.             print 'Exiting part one'
  8.             return
  9.  
  10. def part_two():
  11.     print 'This is part two.'
  12.  
  13. if __name__ == '__main__':
  14.     part_one()
  15.     part_two()
Here is some sample code showing how to write a list of numbers to a file:
Expand|Select|Wrap|Line Numbers
  1. # write a list of numbers to file
  2. # open a file, creating a file object
  3. listofnums = [1,2,3,4,5,6,7,8]
  4. f = open(file_name, 'w')
  5. # convert the number list to a string
  6. numstr = ','.join([str(num) for num in listofnums])
  7. # add newline characters as required
  8. f.write('This is a list of numbers.\n')
  9. f.write('%s\n' % numstr)
  10. # close file object, flush data to disc
  11. f.close()
Mar 6 '08 #9
docdiesel
297 Expert 100+
Hi,

I'm not a Phyton programmer, but may give you another little hint. If calculating up to "number/2" or "(number/2)+1", your program is wasting time. You've just got to check up to the next upper int of the square root.

Next, try to keep them all integers, because most cpus calculate them faster than floats:

Expand|Select|Wrap|Line Numbers
  1. start = 2;
  2. stop  = int (sqrt( number ) + 1 );
  3.  
  4. i = start;
  5. while( i^2 <= stop )
  6. {
  7.   check_if_is_prim(number);
  8.   i++;
  9. }
Regards,

Bernd
Mar 6 '08 #10
bvdet
2,851 Expert Mod 2GB
Hi,

I'm not a Phyton programmer, but may give you another little hint. If calculating up to "number/2" or "(number/2)+1", your program is wasting time. You've just got to check up to the next upper int of the square root.

Next, try to keep them all integers, because most cpus calculate them faster than floats:

Expand|Select|Wrap|Line Numbers
  1. start = 2;
  2. stop  = int (sqrt( number ) + 1 );
  3.  
  4. i = start;
  5. while( i^2 <= stop )
  6. {
  7.   check_if_is_prim(number);
  8.   i++;
  9. }
Regards,

Bernd
Bernd,

Part of the OP's problem is to compile a list of the factors for a given number. To do that, you must go to some point beyond int(sqrt(number))+1. As you pointed out, it is wasting CPU time. Alternatively, you can determine the factors as you suggested and finish out the list with integer division.
Expand|Select|Wrap|Line Numbers
  1. def factors(num):
  2.     outList = [i for i in xrange(2, int(num**0.5)+1) if not num%i]
  3.     outList.extend([num/outList[i] for i in range(len(outList)-1, -1, -1)])
  4.     return outList
Sample:
Expand|Select|Wrap|Line Numbers
  1. >>> factors(1663868945)
  2. [5, 607, 3035, 548227, 2741135, 332773789]
  3. >>> factors(17546598733)
  4. [4259, 4119887L]
  5. >>> 
Other optimizations could be done, but this works fairly well for numbers with less than 14 digits. Thanks for pointing this out. The code I suggested code was a bit too simplistic.
Mar 6 '08 #11
docdiesel
297 Expert 100+
Part of the OP's problem is to compile a list of the factors for a given number.
Uh, I missed that part. I must have been too low on coffee. Furthermore, now I see there're two * in your range condition part "int(n**0.5)+1". I guess that means square root in Python??

Regards,

Bernd (@ home in perl, php and many others, but not in python)
Mar 6 '08 #12
bvdet
2,851 Expert Mod 2GB
Furthermore, now I see there're two * in your range condition part "int(n**0.5)+1". I guess that means square root in Python??

Regards,

Bernd (@ home in perl, php and many others, but not in python)
Yes Bernd. That avoids importing math to access sqrt().
Mar 6 '08 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

36
by: Dag | last post by:
Is there a python module that includes functions for working with prime numbers? I mainly need A function that returns the Nth prime number and that returns how many prime numbers are less than N,...
9
by: Greg Brunet | last post by:
In doing some testing of different but simple algorithms for getting a list of prime numbers, I ended up getting some results that seem a bit contradictory. Given the following test program...
11
by: don | last post by:
Ok, this is a homework assignment, but can you help me out anyway...... I need a routine for figuring out if a number inputted by the user is a prime number or not...... all I'm asking for is Not...
0
by: AshifToday | last post by:
this was my and my frineds little project in earlier classes, the program seperates the composite and prime numbers in two sections of the screen ===================== /* This program has...
0
by: ETM11871 | last post by:
i need to develop a code that finds a prime right number between 2 and 100000. and print one line of text that indicates if the int. is right prime. i am in beginning programing so complex is...
25
by: johnmsimon | last post by:
i need to develop a code that finds a prime right number between 2 and 100000. and print one line of text that indicates if the int. is right prime. i am in beginning programing so complex is...
60
by: rhle.freak | last post by:
Here is my code to generate prime numbers.It works absolutely fine when the range is *not very large*. However on initializing i with a large integer it produces erroneous results (some numbers...
7
by: newstips6706 | last post by:
1, 2, 3, 5, 7... PRIME Numbers ________________________________ Definitions What is a PRIME Number ?
7
by: Caffiend | last post by:
Well, I've been picking at learning python, got tired of reading, and figured I'd try to replicate my prime number generator I wrote (with much TSDN forum help) in C++. I've hit a stumbling block......
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.