473,749 Members | 2,411 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

prime number

I'm having trouble writing a program that figures out a prime number.
Does anyone have an idea on how to write it? All I know is that n > 2
is prim if no number between 2 and sqrt of n (inclusivly) evenly
divides n.

Jul 19 '05 #1
11 5940
On 29 May 2005 19:55:32 -0700, lostinpython
<sh************ ***@hotmail.com > wrote:
I'm having trouble writing a program that figures out a prime number.
Does anyone have an idea on how to write it? All I know is that n > 2
is prim if no number between 2 and sqrt of n (inclusivly) evenly
divides n.
This sounds remarkably like a homework problem, so I'm not going to
give you a full answer. Perhaps if you could be more specific about
which part's giving you trouble we could help you out with that.

If it finding square roots? is it checking for divisibility? is it
getting the loop to run through correctly? Is it some other problem?

Tim

--
http://mail.python.org/mailman/listinfo/python-list

Jul 19 '05 #2
"lostinpyth on" <sh************ ***@hotmail.com > writes:
I'm having trouble writing a program that figures out a prime number.
Does anyone have an idea on how to write it? All I know is that n > 2
is prim if no number between 2 and sqrt of n (inclusivly) evenly
divides n.


How about this (untested):

import sys
import subprocess

primes = subprocess.Pope n(["primes", sys.argv[1], sys.argv[1]],
stdout=subproce ss.PIPE).stdout .readlines()
if primes:
print sys.argv[1], "prime"
else:
print sys.argv[1], "not prime"

Seriously, this sounds like a homework assignment. Google for "sieve
of eratosthenes". The BSD "primes" program I used in the above is an
implementation of that in C.

If it isn't a homework assignment, and you're honestly in such, then
you should know there's been a lot of research in this area, because
primes are important in cryptographic applications. Once again, google
is a good place to start on looking for recent research on the subject.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 19 '05 #3
It is a homework assignment from a book but not for a class. I'm
trying to teach my self some basic programming before I have to take it
in college. If I show enough understanding of the subject, my advisor
will let me forgo Intro. to Programming and go into Intro. to C++.
What civil engineers need with all this programming is beyond me. We
have to learn another language to program our CADD software, which I
find much easier than this. But needless to say, I'm stumped on this
problem. I keep ending up in a never ending loop.

Shanna

Mike Meyer wrote:
"lostinpyth on" <sh************ ***@hotmail.com > writes:
I'm having trouble writing a program that figures out a prime number.
Does anyone have an idea on how to write it? All I know is that n > 2
is prim if no number between 2 and sqrt of n (inclusivly) evenly
divides n.


How about this (untested):

import sys
import subprocess

primes = subprocess.Pope n(["primes", sys.argv[1], sys.argv[1]],
stdout=subproce ss.PIPE).stdout .readlines()
if primes:
print sys.argv[1], "prime"
else:
print sys.argv[1], "not prime"

Seriously, this sounds like a homework assignment. Google for "sieve
of eratosthenes". The BSD "primes" program I used in the above is an
implementation of that in C.

If it isn't a homework assignment, and you're honestly in such, then
you should know there's been a lot of research in this area, because
primes are important in cryptographic applications. Once again, google
is a good place to start on looking for recent research on the subject.

<mike
--
Mike Meyer <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.


Jul 19 '05 #4
lostinpython said unto the world upon 2005-05-30 02:50:
It is a homework assignment from a book but not for a class. I'm
trying to teach my self some basic programming before I have to take it
in college. If I show enough understanding of the subject, my advisor
will let me forgo Intro. to Programming and go into Intro. to C++.
What civil engineers need with all this programming is beyond me. We
have to learn another language to program our CADD software, which I
find much easier than this. But needless to say, I'm stumped on this
problem. I keep ending up in a never ending loop.

Shanna


Hi Shanna,

Since you are just beginning, I'd like to recommend the tutor list
<http://mail.python.org/mailman/listinfo/tutor>. It is not that
newcomers are not welcome here. But the folks who populate the tutor
list are particularly good at answering neophytes' questions at the
level.

Since you've got some code together, even though it isn't doing what
you want, you've already got a decent start for getting help. Post the
question and the code to the tutor list and I'd not be surprised if
you will soon be well on your way to solving your problem.

Best,

Brian vdB
Who owes much of what he knows about Python to the tutor list.

Jul 19 '05 #5
What civil engineers need with all this programming is beyond me.

One of my best friends and expartner and top civil-structural
engineers in the country (he built Dallas Reunion Arena and many
other complex structures) was an ace programmer in many languages.

He was not willing to just accept the results of canned packages,
he wanted to know where the answers came from and make software
that made sense to his engineers.

I presume you are young and if you wish to be an engineer and not
a salesman you must be eaten up with the desire to know
"How Stuff Works". Computers are ubiquitous in engineering
and if you want to be the best, learn how they work.

Jul 19 '05 #6
lostinpython wrote:
But needless to say, I'm stumped on this
problem. I keep ending up in a never ending loop.


I've been told that the trick with recursion/iteration is to always
determine what your ending condition is first, and then construct the
body of the recursion/loop to reach that ending condition eventually. If
you post the specific code which is giving you problems, people here can
point out why you're missing the exit.
Jul 19 '05 #7
lostinpython> I'm having trouble writing a program that figures
lostinpython> out a prime number. Does anyone have an idea on how
lostinpython> to write it?

[I can't quite tell from your posts what your level of programming
knowledge is, so I've aimed low. If this was wrong, please accept my
apologies. --rdh]

It's not quite clear precisely what the problem is. Do you want to
find all primes less than some number N, or find the prime
factorization of some input number, or something else altogether? Are
there any other constraints? Ie, does the program have to be
recursive?

I'm going to assume that you want to find all primes less than N, and
that are no constraints on the form of the program.

First, pretend you have a function called "is_prime". It will look
something like this:

def is_prime(n):
# return True if n is prime, False otherwise
# magic goes here

If we had this function, the our main program would look something
like this:

N = 20
for n in range(1, N+1):
if is_prime(n):
print n

NOTE: range(1,N+1) returns a list of numbers from 1 to N inclusive.

The question now is how to fill in the missing part of is_prime. In
your original post, you noted that n>2 is prime if no number between 2
and sqrt(n) inclusive divides into n evenly.

This tells us that we have to test a list of possible factors for
divisibility into n. Ignoring, for a little while, how we figure out
the possible factors, we can now expand is_prime as follows:

def is_prime(n):
# return 1 if n is prime, 0 otherwise
from math import sqrt
for i in possible_factor s:
# if i divides n, n isn't prime
# if no i divided into n, ie, we fell out of the loop,
# n is prime

The possible factor i divides into n if n % i == 0. Once we've
decided that n is or isn't prime, we can just return True or False
respectively. Adding these details:

def is_prime(n):
# return 1 if n is prime, 0 otherwise
from math import sqrt
for i in possible_factor s:
if n % i == 0:
return True
return False

The final step is to figure out the list of possible factors. By the
definition, this is the list of integers from 2 to the integer value
of sqrt(n), inclusive. To get this list, we can use the range
function again, assuming that sqrt(n) to compute the square root for
us. The list of possible factors is given by

range(2, int(sqrt(n)) + 1)

The final trick to is to get the definition of sqrt. It turns out
that this function is defined in the math module. Adding the bit of
syntax needed to access the sqrt function, we have:

def is_prime(n):
# return 1 if n is prime, 0 otherwise
from math import sqrt
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True

Put together with the main program above, this will print out a list
as follows:

1
2
3
5
7
11
13
17
19

However, there's a slight problem here. By definition, 1 is not a
prime. We could fix this a couple of ways. Either we could change
the main program not to start its range with 1, or we can fix
is_prime. The latter is simple:

def is_prime(n):
# return 1 if n is prime, 0 otherwise
from math import sqrt
if n == 1:
return False
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True

Another algorithm mentioned in the followups to your posting is the
Sieve of Eratosthenes, named for its ancient Greek discoverer. You
can find a description of the Sieve in many places on the web. Trying
to implement it might be a good next step.

Dale.

Jul 19 '05 #8
Sigh ... one of my intermediate versions of is_prime() returns True if
the n is *not* prime, and false otherwise. The final version is
correct, though.

Dale.

Jul 19 '05 #9
lostinpython wrote:
What civil engineers need with all this programming is beyond me. We
have to learn another language to program our CADD software, which I
find much easier than this.


According to my experience, almost every engineer - civil or not - uses
programming at least occationally. So every engineering education
program should involve at least some programming.

/Mikael Olofsson

Universitetslek tor (Senior Lecturer [BrE], Associate Professor [AmE])
Linköpings universitet

-----------------------------------------------------------------------
E-Mail: mi****@isy.liu. se
WWW: http://www.dtr.isy.liu.se/en/staff/mikael
Phone: +46 - (0)13 - 28 1343
Telefax: +46 - (0)13 - 28 1339
-----------------------------------------------------------------------
Linköpings kammarkör: www.kammarkoren.com Vi söker tenorer och basar!
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

36
8396
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
2717
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
7158
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....
2
4233
by: wudoug119 | last post by:
This is my code and it will take any number that I input and say it is a prime number. Please help me... int Prime(int prime) //declares isPrime as a function using integers { int primeCount = 2; //declares primeCount as an int variable and sets it equal to 2 while(primeCount < prime) //checks if primeCount is less than prime {
4
5224
by: SweetLeftFoot | last post by:
Hello, i have designed some code that works out the first 250 prime numbers and prints them to the screen. However i need to implement 2 functions, one of which returns a 1 if the number is a prime and 0 if it isn't. I have spent ages just getting this code to work and i'm worried i need to rip it to bit to get this function to work ! The function is: int prime(int number) here is my code so far: #include...
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
4901
by: newstips6706 | last post by:
1, 2, 3, 5, 7... PRIME Numbers ________________________________ Definitions What is a PRIME Number ?
2
2607
by: QHorizon | last post by:
Hello, I'm new to Python (I've learned everything up to iterators so far) and fairly new to Programming. This would be my first real program: #Coordinate Geometry (The whole program is not shown) import math import sys print "Welcome to the Coordinate Geometry Calculator!"
0
8996
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8832
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
9566
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9388
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...
0
8256
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6078
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
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2791
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2217
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.