Jump to content

Program Care Determină Toate Numerele Prime Mai Mici Sau Egale Cu N


Courage

Recommended Posts

  • Moderators

Sa se scrie un program care determina toate numerele prime mai mici sau egale cu un numar N dat de la tastatura. (n>2)

#include <stdio.h>
#include <math.h>
int i,x,d;
int prim(int i)
{
    for (d=3;d<=sqrt(i);d=d+2)
        if (i%d==0)
            return 0;
    return 1;
}
int main()
{
    scanf("%d", &x);
    printf("2, ");
    for (i=3;i<=x;i=i+2)
    {
        if (prim(i))
            printf("%d, ",i);
    }
    return 0;
}

Mai sus am folosit subprogram :D. Varianta fără subprogram e următoarea:

#include <stdio.h>
#include <math.h>
int i,x,d,OK;
int main()
{
    scanf("%d", &x);
    printf("2, ");
    for (i=3;i<=x;i=i+2)
    {
        OK=1;
        for (d=3;d<=sqrt(i);d=d+2)
            if (i%d==0)
                OK=0;
        if (OK==1)
            printf("%d, ",i);

    }
    return 0;
}
Link to comment
Share on other sites

  • 6 months later...

  • Moderators
#include <iostream>
#include <math.h>

using namespace std;

int main()
{
    int i,x,d,OK;
    cin >> x;
    if (x>1)
    {
        cout << 2 << ' ';
        for (i = 3 ; i<=x ; i = i+2)
        {
            OK = 1;
            for (d = 3 ; d <= sqrt(i) and OK == 1; d = d+2)
                if (i % d == 0)
                    OK = 0;
            if (OK==1)
                cout << i << ' ';
        }
    }
    return 0;
}
Link to comment
Share on other sites

  • 1 month later...

Salut @Courage,

 

Metoda pe care ai folosit-o tu e brute force, corect ?

Dar nu era mai bine folosind Ciurul lui Eratostenes pentru determinarea numerelor prime <= N ?

 

Uite un link pentru mai multe informatii : http://www.infoarena.ro/problema/ciur

 

O zi buna.

  • Upvote 1

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

Link to comment
Share on other sites

  • 1 month later...

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.