Skip to content
This repository has been archived by the owner on Jun 16, 2023. It is now read-only.

Commit

Permalink
ottimizza ricerca numero primo
Browse files Browse the repository at this point in the history
  • Loading branch information
mc-cat-tty committed Nov 16, 2021
1 parent c08ceae commit 467d2f5
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions esercitazioni/numero_primo_ottimizzato.cpp
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
#include <iostream>
#include <math>
#include <cmath>

using namespace std;

// TODO: completa

int main() {
/* struttura dati
Expand All @@ -12,20 +11,21 @@ int main() {
i indice del ciclo for
*/
int n;
bool primo = true; // assumiamo che n sia primo

cin >> n;
if (n>=1 && n<=3) {
cout << "primo" << endl;
cout << n << " è primo" << endl;
return 0;
}

if (n%2==0)
return 0;
primo = false;

int max_div = static_cast<int>(n);
for (int i=4; i<n && primo; i+=2) { // soluzione inefficiente
int max_div = static_cast<int>(sqrt(n));
for (int i=3; i<=max_div && primo; i+=2) {
if (n%i == 0) {
primo = false;
break;
}
}
cout << n;
Expand Down

0 comments on commit 467d2f5

Please sign in to comment.