Jump to content

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


Recommended Posts

  • Moderators
Posted

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;
}
  • 6 months later...

  • Moderators
Posted
#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;
}
  • 1 month later...
  • 1 month later...
  • Moderators
Posted

Salut @Courage,

 

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

 

Salut, da. (am fost plecat ceva vreme şi abia acum am văzut mesajul)

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
  • 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.