Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Prime number task from the book

Tags:

c++

I'm a C++ beginner ;) How good is the code below as a way of finding all prime numbers between 2-1000:

int i, j;

for (i=2; i<1000; i++) {
  for (j=2; j<=(i/j); j++) {
    if (! (i%j))
      break;
    if (j > (i/j))
      cout << i << " is prime\n";
  }
}
like image 747
user377622 Avatar asked Jun 27 '10 23:06

user377622


People also ask

What is prime number example?

Prime numbers are numbers that have only 2 factors: 1 and themselves. For example, the first 5 prime numbers are 2, 3, 5, 7, and 11.

What are the prime number from 1 to 100?

What is the list of prime numbers from 1 to 100? Prime numbers from 1 to 100 are 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.

How do you check if a number is prime or not in C?

Program to Check Prime Number Enter a positive integer: 29 29 is a prime number. In the program, a for loop is iterated from i = 2 to i < n/2 . If n is perfectly divisible by i , n is not a prime number. In this case, flag is set to 1, and the loop is terminated using the break statement.


1 Answers

You stop when j = i. A first simple optimization is to stop when j = sqrt(i) (since there can be no factors of a number greater than its square root).

A much faster implementation is for example the sieve of eratosthenes.

Edit: the code looks somewhat mysterious, so here's how it works:

The terminating condition on the inner for is i/j, equivalent to j<i (which is much clearer),since when finally have j==i, we'll have i/j==0 and the for will break.

The next check if(j>(i/j)) is really nasty. Basically it just checks whether the loop hit the for's end condition (therefore we have a prime) or if we hit the explicit break (no prime). If we hit the for's end, then j==i+1 (think about it) => i/j==0 => it's a prime. If we hit a break, it means j is a factor of i,but not just any factor, the smallest in fact (since we exit at the first j that divides i)! Since j is the smallest factor,the other factor (or product of remaining factors, given by i/j) will be greater or equal to j, hence the test. If j<=i/j,we hit a break and j is the smallest factor of i.

That's some unreadable code!

like image 118
Mau Avatar answered Sep 25 '22 01:09

Mau