Jul 9, 2008

Most Efficient Code To Get Prime Numbers

Free Web Hosting, No Ads > CONTRIBUTE > Computers > Programming Languages > C/C++ Programming

free web hosting

Most Efficient Code To Get Prime Numbers

Csshih
Can anyone write a more efficient code than this to get the prime numbers from 1 -999?
CODE
// Assignment: sieve.cpp
// Purpose: To write the most efficient program
// that outputs prime numbers.

#include<iostream.h>
#include<iomanip.h>
#include<math.h>
// declare constant MAX_NUMBER to be the # of arrays.
const MAX_NUMBER = 1000;


// declare array primes.
bool primes[MAX_NUMBER];
// function prototypes
void initializeArray();
void findMultiples();
void printSubscripts();

int main()
{
// call to functions
initializeArray();
findMultiples();
printSubscripts();
return 0;
}

//*****************************************************
// function initializeArray
//
// Purpose: to initialize the Aray
//
// Input: none
// Output: none
void initializeArray()
{
// start from index 2, ignoring 1 and 0
for(int index = 0; index < MAX_NUMBER; index++)
primes[index] = true;
primes[0] = false;
primes[1] = false;
}

//*****************************************************
// function findMultiples
//
// Purpose: assign false to multiples of prime numbers
//
// Input: none
// Output: none
void findMultiples()
{
int steps = 0;
// for loop, starting the primes at 2, incrementing every loop
for(int index = 2; index < sqrt(MAX_NUMBER); index++)
// if true, then continue
if(primes[index] == true)
// all multiples of primes are assigned false
for(int multiplier = 2; multiplier * index < MAX_NUMBER; multiplier++)
{


primes[multiplier * index] = false;
steps++;
}
cout << "Number of steps are : " << steps << endl;
}



//*****************************************************
// function printSubscripts
//
// Purpose: print prime numbers to console
//
// Input: none
// Output: prime numbers
void printSubscripts()
{
cout << "The prime numbers from 1 to " << MAX_NUMBER-1 << " are:\n" << endl;
// output primes starting from primes[2]
for(int index = 0; index < MAX_NUMBER; index++)
{
if(primes[index])
// a "tab" between every prime number.
cout << index << "\t";
}
cout << endl;
}


Some of the comments may not be correct because I'm just learning programming wink.gif
I'm using Visual C++ 6.0.
Thanks,
Craig

 

 

 


Reply

BuffaloHELP
I haven't programmed in C++ in years, but the above program doesn't look complete. Are you sure the above code produces all prime numbers?

I would imagine you have to double check to see if the number selected between the range is TRUE prime. The best example I can think of is to start dividing a number and work its way down to see the remainder is a whole number. If there are multiple remainders that result in whole numbers, it's not prime.

Such that,

X = a number between 1 and 999

temp = X

//start loop
//set COUNTER = 0
//set REMAINER = 0
//set temp = 0

while temp is NOT equal to 0
REMAINDER = X / temp
IF REMAINDER is a whole number, COUNTER = COUNTER + 1
IF COUNTER is grater than 2, then it's NOT PRIME
ELSE IF COUNTER is equal to 2, then IS PRIME save X to ARRAY
ELSE temp = temp - 1

//exit loop

X = X + 1 and X is not grater than 999

//go back to loop for checking PRIME

Oooohhh... my fuzzy logic looks alright but I'm sure someone will find a flaw in it. Until then you get my point of view. Basically you are picking a number between 1 and 999. Start dividing a chosen number by numbers preceding to the chosen number. If a chosen number is divisible by other numbers (more than twice, itself and 1 which is kept at record by COUNTER) than it is NOT a prime number. And keep on going until X is equal to 999.

 

 

 


Reply

Csshih
When my code gets a prime number, it already removes all multiples of it.
I think that should be complete though.
I compared the output to a online list of primes, it was correct.

Reply

osknockout
A simple idea. Replace your index++'s with index += 2 since there is no other even prime number other than 2.
You're going to have to readjust your code a bit, but it should be worth the ~50% performance increase. laugh.gif

Same thing with your boolean array you don't need to account for any even value besides two, so you could
just have a boolean variable for 2 (or nothing, really) and just have a boolean array for odd number tests.

-Btw, it's generally a good thing if you keep short code in main if you can - particularly if you're only calling
a function only once, makes reading easier. Other than that, seems like nice code. cool.gif

Reply

Csshih
Nice Idea with the index +=2, that should reduce the number of steps by 1/2.
Thanks!
and about the functions,
my teacher said that I have to have only calls to functions in main. >.<

Reply

osknockout
QUOTE
my teacher said that I have to have only calls to functions in main. >.<
Bah! Teachers... I'm so glad I learned C myself.
I for one completely disregard that rule.

You know, looking at the code again, I think if you increased your range
to say 1 to a billion, your technique would not be the most efficient anymore,
but it's the best I can think of right now for low ranges.

Reply

larryf
QUOTE(Csshih @ Dec 18 2007, 11:11 AM) *
Can anyone write a more effecient code than this to get the prime numbers from 1 -999?


Here is an algorithm I wrote using the Rabin/Miller test to test for prime numbers. I even commented it years ago. This is the best way to test for primes, and it will give you all the primes up to MAXINT.

CODE

typedef unsigned int UINT4;

void GetRandomA(UINT4 *a, UINT4 n)
{
*a = rand() % (n - 2) + 1;
}

/* Rabin/Miller test to test a prime number.
Taken from Larry Frieson's Password Manager.
n - 1 = 2km for some k > 0 and odd integer m.
a = 1 < a < n - 1
We say that n passes the Rabin-Miller test for the base a if
either the first term in this sequence is 1, or 1 occurs later
in this sequence and is immediately preceded by -1. If the test
fails, we know that n is composite, and describe the base a as
a witness to the compositeness of n. The crucial extra information
we can derive is that if (odd) n is composite, then at least 3/4
of the numbers a with 1 < a < n - 1 are witness to this fact.
First calculate m, in C++ we do this by simply shifting the bits
right k times, until m is odd and less than n.
Next, we calculate a, such that a is less than n - 1, and a > 1.
Then, we calculate a ^ m mod n. If this result is 1, then
we need to generate a new a and try again. After iIterations, we
can say that n is prime with 1/1024 margin of error.

Two function prototype follow, one for 32 bit integers, one for
multi-precision integers.
*/

int RabinMiller(UINT4 n, int iIterations)
{
srand(100);
int isprime = 0;
UINT4 m = n - 1;
UINT4 k = 0;
UINT4 a = 0;
if((n & 1) == 0) {
return 0;
}
if(m > 0) {
while((m & 1) == 0)
{
k++;
m = (m >> 1);
}
}
GetRandomA(&a, n);
UINT4 r;
do
{
r = 1;
for (int i = 0; i < m; i++)
{
r = (r * a) % n;
}
if(r == 1 || r == (n - 1)) {
GetRandomA(&a, n);
isprime = 1;
continue;
}
for(UINT4 x = 0;x < k + 1;x++)
{
r = (r*r) % n;
if(r == (n - 1)) {
isprime = 1;
break;
}
}
if(isprime == 0) {
break;
}
GetRandomA(&a, n);
}
while(iIterations--);
return isprime;
}


To call the code, you can do it in a loop.

CODE

for(int x = 0;x < 9999;x++)
{
int isPrime = RabinMiller(x, 5);
}


If the return value is non-zero, then the number is prime. And you don't have to worry about skipping even numbers, etc, because the algorithm does it for you.

I used the MPC version of the algorithm (which I left out, because you don't need primes over 32 bit) in a cryptographically secure application with no problems at all.

There is also a Fermat test you can do, which seems a lot like the code you listed...

Larry



Reply

iGuest
Has anyone heard of the AKS algorithm that runs in O(and) time.

-reply by Keertana

Reply



Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Recent Queries:-
  1. prime or composite math.h conio.h stdio.h - 47.25 hr back.
  2. java code-prime number - 141.63 hr back.
  3. code for prime numbers - 691.91 hr back.
  4. rabin-miller cpp - 714.86 hr back.
  5. "online list of primes" - 876.41 hr back.
  6. rabin miller prime c - 877.36 hr back.
Similar Topics

Keywords : efficient, code, prime, numbers

  1. I Need Help
    it's about roman numbers in c/c++ (7)
  2. How I Shall Scan Prime Numbers..
    that is 1,3,5,7,11,13,17,19... (4)
    I want to scan prime numbers ,have you logic to solve this problem? here is example of even
    numbers: CODE
    ----------------------------------------------------------------------------------------------------
    ---------- void main (void) {clrscr(); int a; printf("input any
    no."); scanf("%d"&a); if(a%2=0) {printf("the number is
    even"); getch(); }
    ----------------------------------------------------------------------------------------------------
    -------- Now I want to scan prime numbers....
  3. C++ Roman Numeral Conversion Code Help
    If-else Problem (5)
    thanks....
  4. A Telephone Directory Source Code In C
    (2)
    Well i had made this project some years before. It is a telephone directory which has a very good
    User Interface operatable with scroll key. This code can be usefull in learning about file handling
    and User Interface. CODE #include <stdio.h> #include <box.h> #include
    <conio.h> #include <dos.h> #include <stdlib.h> #include <bios.h>
    #include <graphics.h> FILE *fp; addnew2(char [],char []);
    prnd(); deleteit(); info(); pl(); checkcmd();
    showall(....
  5. Wolfenstein Source Code Now In Public Domain
    (3)
    the Wolfenstein game which we enjoy it alot becouse of its highly graphic technique now u can
    learn alot from it and become profissional programer becouse now its source code in Public Domain
    get the source code now and make your way to become profissional programer get it at
    Wolfenstein source code ....
  6. Source Code For Paint Like Program Under Dos In C
    (2)
    this is a dos program that you have been waiting for you learn from it you how to do graphic
    programing under dos if you understand it your then will be able to do any kind of windows GUI in
    dos it make icons and use them it deal with graphic file youwill also learn how to use mouse have
    nice time ....
  7. Prob With My C Code
    (4)
    Hi Guys! this is a wonderful place.. although i wasnt a member till now i have referred to
    these forms quite a few times for my programming solns /biggrin.gif" style="vertical-align:middle"
    emoid=":D" border="0" alt="biggrin.gif" /> My problem is ::: I am writing a Code in C using
    Bloodshed Dev C++ 4.9.9.2 on Windows XP. I wanted to open an executable file from my code. After
    using the solution mentioned on these forums, I used QUOTE system("myprg"); It works
    fine.. But the prob is that i want my C program to execute this command and then return to t....
  8. Simple C File Handling In Action
    Small code snipet which covers most of basic file handling and navigat (2)
    Yesterday I suddenly got a lot of work. The same work we try to push off, yes you are right all
    formalities to get the code review incorporated and update all source code files with code review
    headers. Imagine if you need to open 300 files one by one and append code review headers at the
    end. Since most files are reviewed in groups of 20 to 30 files. We require one header to be placed
    in say 20 to 30 files. To simplify I went back to my class assignment days and wrote this small c
    utility to open all files passed on command line and open attach code review headers an....
  9. Need Help With C Program To Test If A Number Is Prime
    Ending unexpectedly somewhere near for-loop (12)
    CODE #include <stdio.h> main() {       printf("Enter a number:
    ");              int n;       scanf("%d", &n);              if(n ==
    2)            printf("%d is prime", n);       else if(n % 2 == 0 || n <
    2)            printf("%d is not prime", n);       else       {            int x;
               for(x = 0; x < (int)sqrt((double)n); x++)
                    if(n % x == 0)                 {                      printf("%....
  10. Code Documentation
    A better way? (1)
    This is not so much a question, actually, but a bit of a plug for an interesting tool I've
    discovered recently. Anyway. How does everyone else document their code? Are in-source comments
    sufficient? Do you write extra detailed documentation outside of the code? Or do you generate
    external documentation from the code? Since I've been doing Java recently, I was in awe when I
    discovered javadoc. An incredible tool that allows you to generate external documentation for your
    code from your comments in-source. The syntax is reasonably simple, allowing the comme....
  11. Adding Myfileexists Function To My Basic Code?
    (2)
    Here is a short and basic piece of my first ever application written in Visual C++ 6.0 . I have also
    commented the code well to show you EXACTLY what my code is meant to do with each function. What
    exactly I am asking for, is for someone to please replace anywhere that you see "EXISTS" with the
    proper function "myFileExists" to actually check to see if the file exists. Also I am asking for
    anyone that may see an error in this code, to please point it out to me and how I can fix it. If
    anyone can help me with getting this very basic code to work, it would be GREATLY appr....
  12. C Code, Can U Solve This?
    Another interesting problem (22)
    Hello, Look at the code given below CODE void fun(void) { /* Put your code here so
    that main does not print 20 */ } int main() { int i = 20; fun();
    printf("i = %d\n", i); return 0; } 1. You are allowed to put your code
    ONLY in fun. 2. You are not allowed to change even one character in main. 3. You should not use
    functions like exit(),abort() in the function fun. How do I manipulate and change the value of i?
    Have fun.......
  13. Where Can I Get Full Souce Code Of Turbo C++ ?
    where can i get full souce code of Turbo (2)
    where can i get full souce code of Turbo C++ ? Al... it must be complete... complete... includes and
    libraries... all.. pls.. help me.. coz i cant compile my programs........

    1. Looking for efficient, code, prime, numbers

Searching Video's for efficient, code, prime, numbers
advertisement



Most Efficient Code To Get Prime Numbers



 

 

 

 

ADD REPLY / Got an Opinion! Remove these ADs! RAPID SEARCH! Free Web Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE