473,625 Members | 2,668 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Prime Numbers

7 New Member
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 6208
bvdet
2,851 Recognized Expert Moderator Specialist
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
electric916
7 New Member
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 Recognized Expert Contributor
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 Recognized Expert Moderator Specialist
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
electric916
7 New Member
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 Recognized Expert Moderator Specialist
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
electric916
7 New Member
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 Recognized Expert Moderator Specialist
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 Recognized Expert Contributor
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

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

Similar topics

36
8379
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, but a prime number tester would also be nice. I'm dealing with numbers in the 10^6-10^8 range so it would have to fairly efficient Dag
9
2703
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 (testPrimes.py) with two algorithms that both check for primes by testing only odd numbers using factors up to the square root of the value, where Primes1 is based on all of the existing primes so far, and Primes2 is based on all odd numbers, I would...
11
7152
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 the exact code ( well maybe a little) but the logic or algorithm to tell whether or not a number is prime....
0
2397
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 been made by A & A Group. Muhammad Ali: Roll # 1462 Class A-2 , B.Sc.(Hons.) in C.S.
0
1717
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 complicated. we are on a functions chapter. i am usung the square root to find the prime. so far i have accomplished this but i cant fgure how to divide this by ten so i can find the right prime. i am using c. #include <stdio.h> #include <math.h> ...
25
3873
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 complicated. we are on a functions chapter. i am usung the square root to find the prime. so far i have accomplished this but i cant fgure how to divide this by ten so i can find the right prime. i am using c. #include <stdio.h>
60
1950
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 ending in 5 ..which obviously cannot be prime numbers) can anyone please help me out with the reason?? /*Generate Prime Numbers*/ #include<stdio.h>
7
4896
by: newstips6706 | last post by:
1, 2, 3, 5, 7... PRIME Numbers ________________________________ Definitions What is a PRIME Number ?
7
4126
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... the program is supposed to print onscreen all the prime numbers between two numbers given to it, so if I put in 1 and 10, it should print out 1, 3, 5, 7 (I know, technically 1 isn't considered prime, and 2 should be on there, but otherwise...) ...
0
8182
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8635
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8352
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8494
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6115
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4188
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1800
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1496
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.