ToniDev

Verificare daca un numar N este prim sau nu

Sep 21st, 2023 (edited)
849
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.64 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4.  
  5. bool estePrim(int n) {
  6.     if (n <= 1) {
  7.         return false;  // 0 si 1 nu sunt numere prime
  8.     }
  9.     for (int i = 2; i <= sqrt(n); i++) {
  10.         if (n % i == 0) {
  11.             return false;  // Daca n este divizibil cu i, atunci n nu este prim
  12.         }
  13.     }
  14.     return true;  // Daca a trecut de toate testele, este prim
  15. }
  16.  
  17. int main() {
  18.    
  19.     int n;
  20.  
  21.     cout << "n = ";
  22.     cin >> n;
  23.  
  24.     if (estePrim(n) == true) {
  25.         cout << "Numarul " << n << " este prim" << endl;
  26.     }
  27.     else {
  28.         cout << "Numarul " << n << " nu este prim" << endl;
  29.     }
  30.  
  31.     return 0;
  32. }
Advertisement
Add Comment
Please, Sign In to add comment