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)
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. -
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)
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.
Having trouble still with listing the factors if it is not a prime number. Any advice would be great. Here's what I got. - 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
-
-
-
-
-
if isprime(n) is True:
-
print n, "is a prime number!"
-
if isprime(n) is False:
-
print n, "is not a prime number"
-
print isprime(n)
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.
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. - 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
-
-
-
-
-
if isprime(n) is True:
-
print n, "is a prime number!"
-
if isprime(n) is False:
-
print n, "is not a prime number"
-
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. -
if isprime(n):
-
print n, "is a prime number!"
-
else:
-
print n, "is not a prime number"
-
print isprime(n)
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. - 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
-
if isprime(n):
-
print n, "is a prime number!"
-
else:
-
print n, "is not a prime number"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
n = input ("Please enter a number greater than 2: ")
-
outfile = 'primes-'+str(n)+'.txt'
-
output = open (outfile, "w")
-
def get_factors(n):
-
List1 = []
-
List2 = []
-
List3 = []
-
for x in range(2, int(n**0.5)+1):
-
if n % x == 0:
-
List1 = List1 + [x]
-
for y in List1:
-
c = n / y
-
if c not in List2:
-
List2 = List2 + [c]
-
List3 = List1 + List2
-
List3.sort()
-
return List3
-
def prime_number(n):
-
List4 = []
-
for n in range(2, n+1):
-
if get_factors(n) == []:
-
List4 = List4 + [n]
-
return List4
-
-
p = prime_number(n)
-
output.write(p)
-
print "Found", len(prime_number(n)), "numbers; please check file primes-",n,".txt"
-
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. - 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
-
if isprime(n):
-
print n, "is a prime number!"
-
else:
-
print n, "is not a prime number"
-
-
-
-
-
-
-
-
-
-
-
-
-
-
n = input ("Please enter a number greater than 2: ")
-
outfile = 'primes-'+str(n)+'.txt'
-
output = open (outfile, "w")
-
def get_factors(n):
-
List1 = []
-
List2 = []
-
List3 = []
-
for x in range(2, int(n**0.5)+1):
-
if n % x == 0:
-
List1 = List1 + [x]
-
for y in List1:
-
c = n / y
-
if c not in List2:
-
List2 = List2 + [c]
-
List3 = List1 + List2
-
List3.sort()
-
return List3
-
def prime_number(n):
-
List4 = []
-
for n in range(2, n+1):
-
if get_factors(n) == []:
-
List4 = List4 + [n]
-
return List4
-
-
p = prime_number(n)
-
output.write(p)
-
print "Found", len(prime_number(n)), "numbers; please check file primes-",n,".txt"
-
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). - >>> factorlist = [i for i in range(2, int(297/2.0)+1) if not 297%i]
-
>>> factorlist
-
[3, 9, 11, 27, 33, 99]
-
>>> factorlist = [i for i in range(2, int(97/2.0)+1) if not 97%i]
-
>>> factorlist
-
[]
-
>>>
Skip the function call if the number is 0 with an if statement. - >>> n = 0
-
>>> if n > 1:
-
... print "Proceed"
-
... else:
-
... print "Exit"
-
...
-
Exit
-
>>>
HTH
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.
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: - def part_one():
-
while True:
-
num = int(raw_input("Enter a positive number or 0 to exit."))
-
if num > 0:
-
....call your prime number function here....
-
else:
-
print 'Exiting part one'
-
return
-
-
def part_two():
-
print 'This is part two.'
-
-
if __name__ == '__main__':
-
part_one()
-
part_two()
Here is some sample code showing how to write a list of numbers to a file: - # write a list of numbers to file
-
# open a file, creating a file object
-
listofnums = [1,2,3,4,5,6,7,8]
-
f = open(file_name, 'w')
-
# convert the number list to a string
-
numstr = ','.join([str(num) for num in listofnums])
-
# add newline characters as required
-
f.write('This is a list of numbers.\n')
-
f.write('%s\n' % numstr)
-
# close file object, flush data to disc
-
f.close()
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: - start = 2;
-
stop = int (sqrt( number ) + 1 );
-
-
i = start;
-
while( i^2 <= stop )
-
{
-
check_if_is_prim(number);
-
i++;
-
}
Regards,
Bernd
Sign in to post your reply or Sign up for a free account.
Similar topics |
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
|
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...
|
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....
|
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.
|
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>
...
| |
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>
|
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>
|
by: newstips6706 |
last post by:
1, 2, 3, 5, 7... PRIME Numbers
________________________________
Definitions
What is a PRIME Number ?
|
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...) ...
|
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,...
|
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...
| |
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,...
|
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...
|
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...
|
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();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |