16

This c++ code prints out the following prime numbers: 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97.

But I don't think that's the way my book wants it to be written. It mentions something about square root of a number. So I did try changing my 2nd loop to for (int j=2; j<sqrt(i); j++) but it did not give me the result I needed.

How would I need to change this code to the way my book wants it to be?

int main () 
{
    for (int i=2; i<100; i++) 
        for (int j=2; j<i; j++)
        {
            if (i % j == 0) 
                break;
            else if (i == j+1)
                cout << i << " ";

        }   
    return 0;
}

A prime integer number is one that has exactly two different divisors, namely 1 and the number itself. Write, run, and test a C++ program that finds and prints all the prime numbers less than 100. (Hint: 1 is a prime number. For each number from 2 to 100, find Remainder = Number % n, where n ranges from 2 to sqrt(number). \ If n is greater than sqrt(number), the number is not equally divisible by n. Why? If any Remainder equals 0, the number is no a prime number.)

Sahat Yalkabov
  • 29,198
  • 40
  • 103
  • 171
  • What book are you referring to? – Andrew Marshall Mar 05 '11 at 01:00
  • 12
    If you ever have to generate prime numbers in the future, check out the [Sieve of Eratosthenes](http://en.wikipedia.org/wiki/Sieve_of_eratosthenes) – Marlon Mar 05 '11 at 01:06
  • 10
    @Sahat your book is wrong. 1 is not a prime number. It is neither prime nor composite. – corsiKa Mar 05 '11 at 01:13
  • @glowcoder: I've learned that an hour ago. :) – Sahat Yalkabov Mar 05 '11 at 01:14
  • I'm going to put this as a comment rather than an answer because I know it would get tons of downvotes, but for printing a list of primes from the interval `[1,N]` where `N` fits in an `int`, the best and simplest solution is a single `puts` with a `static const char []` array containing them all. Algorithms to find primes are only interesting for **much** larger values of `N`. – R.. GitHub STOP HELPING ICE Mar 05 '11 at 01:16
  • 3
    @R..: that certainly would generate a downvote from me. Buggered if I'm going to bother downloading a list of all primes up to 2 billion and bloat my code with it, just because computing them myself would be *boring*. – Steve Jessop Mar 05 '11 at 01:20
  • @glowcoder: Just be aware when performing that pedantry that 1 used to be a prime number, then it was inconsistently defined, now it isn't. Granted, the book *is* wrong, since it states that two definitions are equivalent when they aren't. 1 does not have "exactly two different divisors", at least not under any definition by which 2 also has "exactly two different divisors". In the ring of integers there are 2 units (1 and -1), so I suppose actually 1 *does* have 2 divisors at a push. But then 2 has 4 ;-) The exclusion of units from primes, composites and irreducibles is just common sense now. – Steve Jessop Mar 05 '11 at 01:26
  • @R..: and come to think of it, if you wanted to be picky then a program with a string literal over 4095 characters is not guaranteed to compile (translation limits). So how are you initializing that array? I'd say the cutoff for `puts` being best is *well* below `INT_MAX`. My cutoff would be approximately the value at which I could be confident of typing the list myself without error, 2 tries out of 3 :-) – Steve Jessop Mar 05 '11 at 01:38
  • @Steve: The translation limits are best ignored when talking about what's valid C, because a toy compiler is allowed to reject just about any program it wants as long as it compiles *at least one* program that uses features up to each of the translation limits. In any case throw out string literals and use an explicit `char` array if you prefer, or even store the `int` values in an `int` array and loop to print them. By the way, up to pretty large values of `N`, the `static const` array is going to be smaller than the code to generate primes, too. :-) – R.. GitHub STOP HELPING ICE Mar 05 '11 at 02:05
  • 1
    @R..: I dunno, I can write some pretty compact code to generate them, I'd guess the break point on binary size is at most perhaps 100 primes if stored as int (400 bytes of x86 or ARM to generate primes is extravagant, whether the compiler actually emits that is another question), the breakpoint on source size is smaller, but once you pull in `printf` the binary gets larger. Issue with string literals, if we take it seriously (and I sort of agree we don't have to at the level of 4k), applies to arrays too since you need to initialize them in a single "logical source line". – Steve Jessop Mar 05 '11 at 10:42
  • @SteveJessop not that I'd advocate for R..'s position, but you could have a ton of small arrays each initialized to hold its portion of primes, and one huge non-initialized array 2b filled up later by looping through all the smaller arrays. It's a mess. :) Or have 1 non-initialized array and put a lot of assignment statements in a source code. That'd be even a _bigger_ (as in code size) mess. OTOH maximal prime gap in UINT range is 354, so storing half-distances between primes takes 8 bits each for 203.29 mln of them (7bit, for 1st 1mln primes; 6bit, for 1st 100000 prs, huffman-encoded ..?). – Will Ness Oct 01 '12 at 10:04

22 Answers22

33

Three ways:

1.

int main () 
{
    for (int i=2; i<100; i++) 
        for (int j=2; j*j<=i; j++)
        {
            if (i % j == 0) 
                break;
            else if (j+1 > sqrt(i)) {
                cout << i << " ";

            }

        }   

    return 0;
}

2.

int main () 
{
    for (int i=2; i<100; i++) 
    {
        bool prime=true;
        for (int j=2; j*j<=i; j++)
        {
            if (i % j == 0) 
            {
                prime=false;
                break;    
            }
        }   
        if(prime) cout << i << " ";
    }
    return 0;
}

3.

#include <vector>
int main()
{
    std::vector<int> primes;
    primes.push_back(2);
    for(int i=3; i < 100; i++)
    {
        bool prime=true;
        for(int j=0;j<primes.size() && primes[j]*primes[j] <= i;j++)
        {
            if(i % primes[j] == 0)
            {
                prime=false;
                break;
            }
        }
        if(prime) 
        {
            primes.push_back(i);
            cout << i << " ";
        }
    }

    return 0;
}

Edit: In the third example, we keep track of all of our previously calculated primes. If a number is divisible by a non-prime number, there is also some prime <= that divisor which it is also divisble by. This reduces computation by a factor of primes_in_range/total_range.

ProdigySim
  • 2,235
  • 19
  • 17
  • 4
    You could improve your outer loop on the 3rd example: for (int i=3; i<100; i+=2) – ZeroDefect Feb 24 '13 at 01:06
  • 4
    I downvoted: the first example does not consider 2 and 3 to be prime: http://ideone.com/KeOg7l , as the loop is not entered at all. In general I don't think **break** should be considered evil, but when you use it combined with exotic in-loop-stopping-conditions like your if-statement, I would say it definitely is. Moreover, I think your first two examples are equivalent, except that the second uses better code practice and the first is **wrong**. I would also suggest not to do sqrt(x) < y but x < y*y. Finally I think that an accepted answer should mention the Sieve of Eratosthenes. – Herbert May 28 '14 at 19:37
  • @hariszaman to prevent out of bound errors if i is a prime number – oerpli Sep 06 '16 at 15:19
  • instead of juggling the state, a `goto` to the end of the outer loop would suffice, and is exactly the kind of situation where it's called for. `if(prime)...` becomes redundant. – Will Ness Sep 18 '16 at 10:15
  • Hi, could you please explain me the logic of the second way you've written. That will be so great :) Thanks in advance :) – Sreelal TS Sep 26 '18 at 14:41
17

If j is equal to sqrt(i) it might also be a valid factor, not only if it's smaller.

To iterate up to and including sqrt(i) in your inner loop, you could write:

for (int j=2; j*j<=i; j++)

(Compared to using sqrt(i) this has the advantage to not need conversion to floating point numbers.)

sth
  • 200,334
  • 49
  • 262
  • 354
  • 1
    Instead of computing `j*j` at each step, you can use the fact that `(j+1)*(j+1)=j*j+2*j+1` to keep a running accumulator for `j*j`. I would say let the compiler do that, but my faith in compilers is failing these days... – R.. GitHub STOP HELPING ICE Mar 05 '11 at 02:07
  • to avoid overflow, can use `j <= i/j`. not here, obviously. :) – Will Ness Oct 24 '18 at 19:06
12

If a number has divisors, at least one of them must be less than or equal to the square root of the number. When you check divisors, you only need to check up to the square root, not all the way up to the number being tested.

Jerry Coffin
  • 437,173
  • 71
  • 570
  • 1,035
7

This is my very simple c++ program to list down the prime numbers in between 2 and 100.

for(int j=2;j<=100;++j)
{
    int i=2;
    for(;i<=j-1;i++)
    {
        if(j%i == 0)
            break;
    }

    if(i==j && i != 2)
        cout<<j<<endl;
}
Carthi
  • 255
  • 4
  • 6
5

Using Sieve of Eratosthenes logic, I am able to achieve the same results with much faster speed.

My code demo VS accepted answer.

Comparing the count, my code takes significantly lesser iteration to finish the job. Checkout the results for different N values in the end.

Why this code performs better than already accepted ones:

- the even numbers are not checked even once throughout the process.

- both inner and outer loops are checking only within possible limits. No extraneous checks.

Code:

int N = 1000; //Print primes number from 1 to N
vector<bool> primes(N, true);
for(int i = 3; i*i < N; i += 2){    //Jump of 2
    for(int j = 3; j*i < N; j+=2){  //Again, jump of 2
        primes[j*i] = false;
    }
}
if(N >= 2) cout << "2 ";
for(int i = 3; i < N; i+=2){        //Again, jump of 2
    if(primes[i] == true) cout << i << " "; 
}

For N = 1000, my code takes 1166 iterations, accepted answer takes 5287 (4.5 times slower)

For N = 10000, my code takes 14637 iterations, accepted answer takes 117526 (8 times slower)

For N = 100000, my code takes 175491 iterations, accepted answer takes 2745693 (15.6 times slower)

Saurav Sahu
  • 9,755
  • 5
  • 42
  • 64
  • One serious problem with the first solution from the accepted answer is that it (nominally) calls `sqrt(i)` in each iteration of the inner loop. A good optimizer might manage to optimize that out. The other serious problem with the first solution is that it re-establishes primality from scratch for each value. Any solution that caches previous prime information (any sieve-like solution) will quickly outperform that — unless the range is so small (like up to 100) that the overhead of the cache outweighs the cost of evaluation. For 'up to one million', it would be awful. – Jonathan Leffler Sep 18 '16 at 05:08
  • Note that the third solution in the accepted answer uses caching of previous primes — how does that compare with your solution? – Jonathan Leffler Sep 18 '16 at 05:13
  • @JonathanLeffler that is also 4 times slower for N = 100000, it takes 744435. http://ideone.com/akoiaP – Saurav Sahu Sep 18 '16 at 05:19
  • 1
    @will... which calculations you find redundant... could you please exactly pin point? – Saurav Sahu Sep 18 '16 at 13:04
  • compare with [my answer](http://stackoverflow.com/a/12543821/849891). does it clarify things for you? – Will Ness Sep 18 '16 at 13:07
  • to clarify, there's one specific thing to fix in your code, and the change is minuscule... err, sorry, no, one change is very small indeed, but there's one more. right now your sieve is not even the sieve of Eratosthenes. – Will Ness Sep 18 '16 at 13:09
  • 1
    @WillNess just thinking...will your code change a lot if I have to find the prime number from 1 to 10000 or more. About your last comment: yes, my program is a modified version of sieve of Eratosthenes, which skips any short of even number in the process.. – Saurav Sahu Sep 20 '16 at 05:57
  • @SauravSahu yes, of course it would have to be changed a whole lot. -- What I was aiming at are two things: **1.** start from square, not from a 3x multiple. **2.** Sieve of _Eratosthenes_ eliminates multiples of _primes_, not just of _all odd numbers_ (which is valid of course, just less efficient). – Will Ness Sep 20 '16 at 09:25
  • You can still do better. First, replace the condition `i*i < N` with `i < sqrt_N` with precomputed `sqrt_N`. Second, replace the initialization `int j = 3` with `int j = i`. Third, replace `i*j` with `k`, so that the cycle is `for (int k = i * i; k <= N; k += 2 * i) primes[k] = false;`. – Evg Nov 26 '17 at 13:00
  • @Evgeny and it *still* won't be the sieve of *Eratosthenes* after that. – Will Ness Nov 27 '17 at 17:16
4

actually the better solution is to use "A prime sieve or prime number sieve" which "is a fast type of algorithm for finding primes" .. wikipedia

The simple (but not faster) algorithm is called "sieve of eratosthenes" and can be done in the following steps(from wikipedia again):

  1. Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
  2. Initially, let p equal 2, the first prime number.
  3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These numbers will be 2p, 3p, 4p, etc.; note that some of them may have already been marked.
  4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
Fady Mohamed Othman
  • 1,863
  • 1
  • 15
  • 21
3

Finding primes up to a 100 is especially nice and easy:

    printf("2 3 ");                        // first two primes are 2 and 3
    int m5 = 25, m7 = 49, i = 5, d = 4;
    for( ; i < 25; i += (d=6-d) )
    {
        printf("%d ", i);                  // all 6-coprimes below 5*5 are prime
    }
    for( ; i < 49; i += (d=6-d) )
    {
        if( i != m5) printf("%d ", i);
        if( m5 <= i ) m5 += 10;            // no multiples of 5 below 7*7 allowed!
    }
    for( ; i < 100; i += (d=6-d) )         // from 49 to 100,
    {
        if( i != m5 && i != m7) printf("%d ", i);
        if( m5 <= i ) m5 += 10;            //   sieve by multiples of 5,
        if( m7 <= i ) m7 += 14;            //                       and 7, too
    }

The square root of 100 is 10, and so this rendition of the sieve of Eratosthenes with the 2-3 wheel uses the multiples of just the primes above 3 that are not greater than 10 -- viz. 5 and 7 alone! -- to sieve the 6-coprimes below 100 in an incremental fashion.

Will Ness
  • 62,652
  • 8
  • 86
  • 167
2

It's fine to change your for loop to for (int j=2; j<=sqrt(i); j++) but then you also need to change something else. Looking specifically at your print condition,

else if (i == j+1) {
      cout << i << " ";
}

why will that never be triggered if you only iterate up to sqrt(i)? Where can you move the cout to to change this? (Hint: you may want to move the print out of the loop and then make use of some type of flag variable)

Jesse Cohen
  • 3,950
  • 20
  • 24
2

I check if a number is prime or not with the following code( of course using sqrt ):

bool IsPrime(const unsigned int x)
{
  const unsigned int TOP
  = static_cast<int>(
      std::sqrt( static_cast<double>( x ) )
    ) + 1;

  for ( int i=2; i != TOP; ++i )
  {
    if (x % i == 0) return false;
  }
  return true;
}

I use this method to determine the primes:

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

#include <cmath>

void initialize( unsigned int *, const unsigned int );
void show_list( const unsigned int *, const unsigned int );
void criba( unsigned int *, const unsigned int );
void setItem ( unsigned int *, const unsigned int, const unsigned int );

bool IsPrime(const unsigned int x)
{
  const unsigned int TOP
  = static_cast<int>(
      std::sqrt( static_cast<double>( x ) )
    ) + 1;

  for ( int i=2; i != TOP; ++i )
  {
    if (x % i == 0) return false;
  }
  return true;
}

int main()
{

    unsigned int *l;
    unsigned int n;

    cout << "Ingrese tope de criba" << endl;
    cin >> n;

    l = new unsigned int[n];

    initialize( l, n );

    cout << "Esta es la lista" << endl;
    show_list( l, n );

    criba( l, n );  

    cout << "Estos son los primos" << endl;
    show_list( l, n );
}

void initialize( unsigned int *l, const unsigned int n)
{
    for( int i = 0; i < n - 1; i++ )
        *( l + i ) = i + 2;
}

void show_list( const unsigned int *l, const unsigned int n)
{
    for( int i = 0; i < n - 1; i++ )
    {
        if( *( l + i ) != 0)
            cout << l[i] << " - ";
    }
    cout << endl;
}

void setItem( unsigned int *l, const unsigned int n, const unsigned int p)
{
    unsigned int i = 2;
    while( p * i <= n)
    {
        *( l + (i * p - 2) ) = 0;
        i++;
    }
}

void criba( unsigned int *l, const unsigned int n)
{
    for( int i = 0;  i * i <= n ; i++ )
     if( IsPrime ( *( l + i) ) )
        setItem( l, n, *(l + i) );      
}
fpointbin
  • 1,443
  • 3
  • 14
  • 20
1

The book seems to be "C++ for Engineers and Scientists" written by Gary Bronson (googled it).
Is this a possible answer? IMHO it's surprising.

I had to read the question (from the book) a few times. My interpretation:
For each number N: 2 <= N < 100 check whether it's prime.
How? For each divisor D: 2 <= D < sqrt(N) ,
if D divides N, N is not prime, if D > sqrt(N), N is prime.

Give it a try:

N = 2, sqrt(2) ≈ 1.41, D = 2, 2 < 1.41 ?  no 2 > 1.41 ? yes 2 is prime.  
N = 3, sqrt(3) ≈ 1.73, D = 2, 2 < 1.73 ?  no 2 > 1.73 ? yes 3 is prime.  
N = 4, sqrt(4) = 2.00, D = 2, 2 < 2.00 ?  no 2 > 2.00 ?  no 4 is not prime.  
N = 5, sqrt(5) ≈ 2.24, D = 2, 2 < 2.24 ? yes 5 % 2 > 0? yes  
                       D = 3, 3 < 2.24 ?  no 3 > 2.24 ? yes 5 is prime.    
N = 6, sqrt(6) ≈ 2.45, D = 2, 2 < 2.45 ? yes 6 % 2 = 0  2 > 2.45 ? no 6 is not prime.

As far as I can see, that's how the primes should be found,
not with a sieve (much, much faster),
but with: the answer is in the question! Surprising?

Speed? primes < 400,000 : less than 10 seconds (on my watch, a rolex, I bought it on the market, the seller said it was a real one, a real one for the price of two baguettes, with 12 real diamonds as well).
Let's count the primes (I'm not going to show code ;) : 664579 primes < 10,000,000 : 5 seconds.

#include "stdafx.h"
#include <math.h>
#include <iostream>
using namespace std;
int main()
{
    double rt;
    for (int d = 2, n = 2; n < 100; d = 2, n++)
    {
        for (rt = sqrt(n); d < rt; d++)
            if (n % d == 0) break;
        if (d > rt) cout << n << " ";
    }
    getchar();  // 25 primes :-)
}

Deleted an earlier answer with (like other answers) a prime-sieve.
Hopefully I get my next "Necromancer" badge soon.

I asked the author: In your book: "C++ for E&S" is an exercise about prime numbers,[xrcs]...[/xrcs]. Seven years ago it was asked at: SO/q/5200879
A few days ago I gave an answer: SO/a/49199435
Do you think it is a reasonable solution, or perhaps the solution.

He replied: Peter, I never really have a specific solution in mind when I am making up the exercises,
so I can’t say I had your exact solution in mind. The joy of C++ is that one can come up with really creative solutions and great code, as, on first glance, it looks like you have done.
Thanks for sending it!
Dr. Bronson

I went to https://youtu.be/1175axY2Vvw

PS. A sieve: https://pastebin.com/JMdTxbeJ

P_P
  • 647
  • 7
  • 10
  • you'd have to get 5 up votes for that badge! so perhaps you need to add more discussion (what is it that's "surprising" here? what's wrong with the sieves?), comparison with other answers for speed (or memory footprint?), etc., for that. :) – Will Ness Mar 12 '18 at 13:47
  • @Will Ness: I forgot about the memory footprint, it's nada, ie zero, which isn't to bad. Five up votes? That's going to take at least fifty years, for a true necromancer a split second. – P_P Mar 13 '18 at 00:37
0

Here is my implementation of Sieve of Eratosthenes (for primes between 2 & n)

#include <iostream>

int main (){
int n=0;
std::cout << "n = ";
std::cin >> n;
std::cout << std::endl;

if (n==0 || n==1){
    std::cout << "No primes in this range" << std::endl;
    return 0;
}


const int array_len = n-2+1;

int the_int_array[array_len];
for (int counter=2; counter <=n; counter++)
    the_int_array[counter-2]=counter;


int runner = 0;
int new_runner = 0;

while (runner < array_len ){
    if (the_int_array[runner]!=0){
        new_runner = runner;
        new_runner = new_runner + the_int_array[runner];

        while (new_runner < array_len){
           the_int_array[new_runner] = 0;
           new_runner = (new_runner + the_int_array[runner]);
        }
    }
runner++;
}

runner = 0;

while (runner < array_len ){
    if (the_int_array[runner]!=0)
        std::cout << the_int_array[runner] << " ";
    runner++;
}

std::cout << std::endl;
return 0;

}

pravish
  • 33
  • 8
  • Note that this code uses a variable length array, VLA, at `int the_int_array[array_len];` and G++ will admit that's a non-standard extension if you specify `-pedantic` amongst the compilation options. VLAs are a (useful) feature of C99 and later, but not strictly a part of C++. There are ways to work around this — `vector` springs to mind. – Jonathan Leffler Sep 18 '16 at 05:29
0
#include "stdafx.h"
#include<iostream>
using namespace std;
void main()
{ int f =0;
 for(int i=2;i<=100;i++)
  {
   f=0;
   for(int j=2;j<=i/2;j++)
   { 
     if(i%j==0)
     { f=1;
       break;
     }
   }
 if (f==0)
  cout<<i<<" ";
}
 system("pause");
}
Mohsin
  • 1
0

this is my approach from a simple blog:

//Prime Numbers generation in C++
//Using for loops and conditional structures
#include <iostream>
using namespace std;

int main()
{
int a = 2;       //start from 2
long long int b = 1000;     //ends at 1000

for (int i = a; i <= b; i++)
{

 for (int j = 2; j <= i; j++)
 {
    if (!(i%j)&&(i!=j))    //Condition for not prime
        {
            break;
        }

    if (j==i)             //condition for Prime Numbers
        {
              cout << i << endl;

        }
 }
}
}

- See more at: http://www.programmingtunes.com/generation-of-prime-numbers-c/#sthash.YoWHqYcm.dpuf

0

I always use this one (it's easy and fast) :

#include <iostream>
using namespace std;

int i,j;
bool b[101];

int main( )
{
    for(i=2;i<101;i++){
        b[i]=true;
    }
    for(i=1;i<101;i++){
        if(b[i]){
            cout<<i<<" ";
            for(j=i*2;j<101;j+=i) b[j]=false;
        }
    }
}

Here is output of this code: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

Zaeem Sattar
  • 848
  • 2
  • 10
  • 27
0

To find whether no. is prime or not C++:

#include<iostream>
#include<cmath>

using namespace std;
int main(){

int n, counter=0;

cout <<"Enter a number to check whether it is prime or not \n";
cin>>n;

  for(int i=2; i<=n-1;i++) {
    if (n%i==0) {
      cout<<n<<" is NOT a prime number \n";
      break;
    }
    counter++;
                }
    //cout<<"Value n is "<<n<<endl;
    //cout << "number of times counter run is "<<counter << endl;
    if (counter == n-2)
      cout << n<< " is prime \n";
   return 0;
}
sachinjain024
  • 19,669
  • 27
  • 88
  • 154
Sdembla
  • 1,429
  • 11
  • 13
0

I did it in perl based on the most popular answer by ProdigySim's 2nd method. I had to add a break equivalent in perl, last, right after the print $i . " \n"; to avoid outputting the primes twice.

#!/bin/perl
use strict;

for(my $i=2; $i < 100; $i++){

    my $prime = 1;

    for (my $j=2; $j*$j<=$i; $j++){
        if ($i % $j == 0){
            $prime = 0;
            last;
        }
        if($prime) {
            print $i . " \n";
            last;
        }
    }

}
  • 1
    The question is about C++. I'm not sure about stackoverflow's policy on posting solutions in a different language, but your answer would certainly benefit many more people by being tagged `perl`. You should consider deleting it here and either a) finding a similar perl question, or b) posting a similar question yourself, tagging it `perl`, and answering it with this post. – savanto May 07 '14 at 16:39
0

A simple program to print "N" prime numbers. You can use N value as 100.

    #include  <iostream >
    using  namespace  std;

    int  main()
    {
        int  N;
        cin  >>  N;
        for (int  i =  2;  N > 0;  ++i)
        {
            bool  isPrime  =  true ;
            for (int  j =  2;  j < i;  ++j)
            {
                if (i  % j ==  0)
                {
                    isPrime  =  false ;
                    break ;
                }
            }
            if (isPrime)
            {
                --N;
                cout  <<  i  <<  "\n";
            }
        }
        return  0;
    }
Dineshkumar
  • 1,257
  • 3
  • 21
  • 43
0

here is a simple code for printing all the prime numbers until given number n,

#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
int n,i,j,k;
cout<<"Enter n\n";
cin>>n;

for(i=1;i<=n;i++)
{   k=0;
  for(j=1;j<=i;j++)
  {
    if((i%j)==0)
    k++;
   }
  if(k==2)
  cout<<i<<endl;
}
getch();
}
palslav
  • 1
  • 1
0

Using the rules of divisibility prime numbers can be found out in O(n) and it`s really effecient Rules of Divisibility

The solution would be based on the individual digits of the number...

NirmalGeo
  • 763
  • 4
  • 11
0

While this is relatively more production grade prime number generator, it is still valid to use for finding prime numbers from 1 through 100. The code uses Miller-Rabin Primality Test to achieve calculate prime numbers. Since it is probabilistic method, the accuracy increases with value of k. While the focus is on readability of code rather than speed, on AWS r5.2xlarge instance it took 3.791s for prime number until 1,000,000.

// C++ program to print all primes smaller than or equal to 
// n using Miller-Rabin Primality Test
// Reference: https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
// It is not particularly to optimized 
// since focus is readability
// Compile: g++  -std=c++17 -o prime prime.c++ -ltbb 

#include <execution>
#include <iostream>
#include <math.h>
using namespace std; 

int power(unsigned long int x, unsigned long y, unsigned long p){
    int res = 1;
    x = x % p;
    while (y > 0) {
        if (y & 1)
            res = (res * x) % p;
        y = y >> 1;
        x = (x * x) % p;
    }
    return res;
}

bool millerTest(unsigned long d, unsigned long n) {
    unsigned long a = 2 + rand () % (n - 4);

    unsigned long x = power(a, d, n);

    if (x == 1  || x == n - 1)
        return true;

    while (d != n - 1){
        x = (x * x) % n;
        d *= 2;
        if (x == 1) return false;
        if (x == n - 1) return true;

    }
    return false;
}

bool isPrime(unsigned long n, int k) {
    if (n <= 1 || n == 4) return false;
    if (n <= 3) return true;

    unsigned long int d = n - 1;
    while (d % 2 == 0)
        d /= 2;
    for(int i = 0; i < k; i++){
        if (!millerTest(d, n))
            return false;
    }
    return true;
}




int main() 
{ 
    int n = 1000000;
    int k = 200; 
    vector<unsigned long> primeN(n);
    iota(primeN.begin(), primeN.end(), 1);

    vector<bool> isPrimeV(n);



    transform(execution::par,
        primeN.begin(), primeN.end(), 
        isPrimeV.begin(), 
        [k](unsigned long x) -> bool {
            return isPrime(x, k);
        });

    int count = accumulate(isPrimeV.begin(), isPrimeV.end(), 0, [](int d, bool v){
        if (v == true) return d += 1; else return d;
    });
    cout << count << endl;

    return 0; 
} 

Supreet Sethi
  • 1,594
  • 13
  • 23
0
#include<iostream>
using namespace std;
void main()
{
        int num,i,j,prime;
    cout<<"Enter the upper limit :";
    cin>>num;
    cout<<"Prime numbers till "<<num<<" are :2, ";

    for(i=3;i<=num;i++)
    {
        prime=1;
        for(j=2;j<i;j++)
        {
            if(i%j==0)
            {
                prime=0;
                break;
            }
        }
        if(prime==1)
            cout<<i<<", ";
    }
}
Gaurav
  • 25
  • 1
  • This the perfect code to find the number of prime numbers below a given number. – Gaurav Mar 11 '12 at 17:02
  • 2
    Imperfection lies in the time-complexity of this, you can improve it by changing inner loop as j*j < i – Pungs Sep 17 '13 at 13:24
-1

Just try this. It's easy without any extra builtin functions.

#include <iostream>

int prime(int n,int r){

  for(int i=2;n<=r;i++){
    if(i==2 || i==3 || i==5 || i==7){
      std::cout<<i<<" ";
      n++;
    } else if(i%2==0 || i%3==0 || i%5==0 || i%7==0)
      continue;
    else {
      std::cout<<i<<" ";
      n++;
    }
  }

}

main(){

  prime(1,25);
}

Testing by 2,3,5,7 is good enough for up to 120, so 100 is OK.

There are 25 primes below 100, an 30 below 121 = 11*11.

Will Ness
  • 62,652
  • 8
  • 86
  • 167
Osama Sheikh
  • 844
  • 1
  • 10
  • 14