D
D
Decoy_12018-04-23 01:40:45
Mathematics
Decoy_1, 2018-04-23 01:40:45

Looking for prime numbers?

Hello everyone, help with the program for finding prime numbers from the textbook:

#include <iostream>
#include<conio.h>
using namespace std;

int main()
{
  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 << " - simple number\n";
  }
  _getch();
return 0;
}

Why and for what purposes these checks:
for (j = 2; j <= (i / j); j++){ -- why is the i/j range taken
if (!(i % j)){
if (j > (i / j)) cout << i << "-simple number\n";

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2018-04-23
@longclaps

Let's say i is composite, i.e. decomposes into p 1 *p 2 *..*p n , then, to make sure that it is composite, it is enough to find its smallest divisor (let it be p 1 ).
But it is definitely not greater than the product of the remaining divisors (p 2 *..*p n ) == i / p 1 - that's all.

I
Igor, 2018-04-23
@assembled

As for the longclaps range , I wrote it correctly, I will explain the rest:
This block of code:

if (!(i % j)){
    break;
}

checks whether i is evenly divisible by j, if the remainder of dividing i % j is 0, then the number i is composite and it makes no sense to sort through the remaining divisors, and the inner loop is interrupted.
The condition if (j > (i / j))checks whether the cycle of iterating over divisors has completely ended, if j > (i / j) means that the inner loop was not interrupted, which means that there were no divisors for i, and therefore it is simple and i is displayed on the screen.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question