Jump to content

Tutorial Algoritm Verificare Numar Prim In C++


Gabriel™

Recommended Posts

Se verifica prin impartirea numarului repetat de la 2 la radical din acesta. Daca exista o impartire cu rest 0 (=impartire buna) inseamna ca numarul nu este prim.

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

int main() {
int ok=0, i, n;
cout<<"n= "; cin>>n;
for(i=2; i<=sqrt(n); i++)
if(n%i==0) ok=1;
if(ok) cout<<"Nu este prim.";
else cout<<"Este prim.";
_getch();
} 
Link to comment
Share on other sites

  • Moderators

Si de ce vrei sa calculezi sqrt(n) de fiecare data cand incrementezi i?

#include <cmath>
bool prim(int numar)
{
    if (numar % 2 == 0 || numar < 3)
    {
        return numar == 2;
    }
    unsigned int sq_root = sqrt(numar);
    for (unsigned int diviz = 3; diviz <= sq_root; diviz += 2)
    {
        if (numar % diviz == 0)
        {
            return false;
        }
    }
    return true;
}
Link to comment
Share on other sites

  • 2 weeks later...

Nu cred ca se calculeaza sqrt(n) de fiecare data. Compilatorul ar trebui sa optimizeze chestia aia si sa se apeleze doar o data.

 

Defapt se calculeaza de fiecare data sqrt(n), dar pentru ca sqrt-ul mai da rateuri uneori, era mai lejer asa:

for(int i = 2; i * i <= n; ++i) {
    ...
}

Daca iti iese un program din prima, inseamna ca ceva e gresit...

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.