Prime number generation algorithm

前端 未结 3 601
渐次进展
渐次进展 2020-12-21 13:02

Please look at the following and see if you could advise.

cout << \"2\" << endl;
cout << \"3\" << endl;

ofstream of(\"Primes.txt\");         


        
相关标签:
3条回答
  • 2020-12-21 13:47

    here is the most simplest logic:

    //Prime Numbers generation in C++
    //Using for loops and conditional structures
    #include <iostream>
    using namespace std;
    
    int main()
    {
    int a = 2;       //start from 2
    long long int b = 1000;     //ends at 1000
    
    for (int i = a; i <= b; i++)
    {
    
     for (int j = 2; j <= i; j++)
     {
        if (!(i%j)&&(i!=j))    //Condition for not prime
            {
                break;
            }
    
        if (j==i)             //condition for Prime Numbers
            {
                  cout << i << endl;
    
            }
     }
    }
    }
    
    0 讨论(0)
  • 2020-12-21 13:47
      #include<stdio.h>
    int main(void)
    {int x,i,l;
    printf("number of enter test cases\n");
    scanf("%d",&x);
    if(x>10)
    {
        return;
    }
    printf("enter the range(please do not enter 1)\n");
    int mx[20];
     for(i=0;i<x*2;i=i+2)
     {
         scanf("%d%d",&mx[i],&mx[i+1]);
         if(mx[i]==1)
         {
          return;
         }
         }
           for(l=0;l<x*2;l=l+2){
    
         check(mx[l],mx[l+1]);
       }
      return 0;
    
     }
    void check(int m,int n)
      { //for checking number is prime number or not
      int j,k;
     int flag;
     for(j=m;j<=n;j++)
      {   flag=0;
    for(k=2;k<j;k++)
       {
           if(j%k==0)
             {
             flag++;
             }
      }
         if(flag==0)
       {
          printf("\n%d\n",j);
    
        }
    
     }
    
    0 讨论(0)
  • 2020-12-21 13:49

    Eliminating numbers dividable by prime numbers (2,3,5,7 etc.) is a not soo bad idea when you look for a list of (small) prime numbers but you should use the newly found prime numbers too to be sure that the list contains only primes (not only 2,3,5,7 but also those passing: 11,13,17 etc.)

    For bigger primes (you just can't calculate the way explained if the numbers are too big as you need to check almost all numbers (say each 4-5 anyhow) from 1 to the number to check), the usual approach is to take a random big number and check if it passes Fermats Small Theorem with say 3,5,7 and 11 (IIRC the probability for it to be a non prime if it passes with just 3,5,7 and 11 is really improbable).

    Check out Fermats primality test for a more hands on explanation.

    0 讨论(0)
提交回复
热议问题