ToniDev

Afisare toate numerele prime pana la N

Sep 21st, 2023 (edited)
760
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.67 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <cmath> // pentru sqrt() -> square root -> radical
  3. using namespace std;
  4.  
  5. int main() {
  6.     int n;
  7.  
  8.     cout << "n = ";
  9.     cin >> n;
  10.  
  11.     // check if a number is prime and print it
  12.     for (int i = 2; i <= n; i++) {
  13.  
  14.         bool isPrime = true; // assume the number is prime
  15.         for (int j = 2; j <= sqrt(i); j++) {
  16.             if (i % j == 0) { // if the number is divisible by j then it is not prime
  17.                 isPrime = false; // so we change the value of isPrime to false
  18.                 break; // and we stop the loop
  19.             }
  20.         }
  21.  
  22.         if (isPrime) { // if the number is prime then we print it
  23.             cout << i << " ";
  24.         }
  25.     }
  26.  
  27.     return 0;
  28. }
Advertisement
Add Comment
Please, Sign In to add comment