Prime Number Product (Large Number Multiplication+Ess Sieve Method)

Product of prime numbers

Title description
TWQ is frantically brushing questions every day, and today I got a water question, so hurry up and get a blood, give you a positive integer n, find the product of all prime numbers in a number less than n, enter multiple sets of test cases, 0 is the end sign, and the initial value of the product of all prime numbers is 0.

Enter a
positive integer n (n<=10000)

Output
is the product of prime numbers less than n.

Sample input
5
0

Sample output
6

Tips for
multiplication of large numbers

#include<stdio.h>
#include<math.h>
int a[1000000];
int main()
{
    
    
    int i,j,f=0,k,l1,l2,x,y,z,n,l,b[10010];
    //标记10000以内的素数
    for(i=0;i<=10000;i++)
        b[i]=1;//先把所有数标位1
    for(i=2;i<=100;i++)//前100的质数就能筛出来所有质数了
        {
    
    
            if(b[i])//如果b[i]==1则就是素数
            {
    
    
               for(j=i+i;j<=10000;j=j+i)//埃氏筛法,所有是i的倍数全部不是素数,标记为0
                b[j]=0;//标记所有不是质数的数
            }
        }
 
     while(scanf("%d",&n)!=EOF)
    {
    
    
        if(n<=0)
        break;
        for(i=1;i<1000000;i++)
        a[i]=0;//把数组初始化为0方便后面计算因为0*任何数都是0
        a[0]=1;//大数乘法首位为1去乘每一位
        if(n==1||n==2)//特判
        printf("0\n");
        else
        {
    
    
        for(i=2;i<n;i++)//遍历n以内的素数
        {
    
    
            if(b[i])//i是素数
            {
    
    
                 y=0;
            for(j=0;j<7000;j++)//遍历7000简单粗暴
            {
    
    
                x=a[j]*i+y;//每一位*i
                a[j]=x%10;//保留个位存入数组a
                y=x/10;//计算进位
            }
            }
        }
        for(i=5000;i>=0;i--)//首先遍历找出第一个不为0的数即是最高位
         if(a[i]!=0)
         break;
         for(j=i;j>=0;j--)//循环遍历
         printf("%d",a[j]);
        printf("\n");
       }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/m0_46381590/article/details/111420393