NYOJ 225题 小明求素数积

应用到的知识点:

1.筛选素数(见素数);

2.大数乘法(见求高精度幂);

要注意的是:后六位不能以0开头!

 

01.   
02.#include<stdio.h>
03.#include<string.h>
04.intmain()
05.{
06.    booln[1000] = {0};//标记所有的素数;
07.    inti, j;
08.    for(i = 2; i * i <= 1000; i ++)
09.    {
10.        if(n[i] == 0)
11.        for(j = i + i; j <= 1000; j += i )
12.        {
13.            n[j] = 1;
14.        }
15.    }
16.    intT;
17.    scanf("%d", &T);
18.    while(T --)
19.    {
20.        intN;
21.        scanf("%d", &N);
22.        intinput[2000] = {0}, temp[2000] = {0}, output[2000] = {2};
23.        intnum,   out = 1, k = 0, m = 0;//in,input中元素个数;out,output中元素的个数;
24.        for(i = 3; i <= N; i ++)//模拟手算;
25.        {
26.            intj = 0,in = 0;
27.            if(n[i] == 0)//针对所有素数;
28.            {
29.                num = i;
30.                while(num != 0)
31.                {
32.                    input[j ++] = num % 10;
33.                    num /= 10;
34.                    in ++;
35.                }//将素数一位一位地,倒序地,存到input数组里面;
36.                for(j = 0; j < in; j ++)
37.                {
38.                    intl = j, s[2000] = {0}, c[2000] = {0};
39.                    for(k = 0; k < out; k ++)
40.                    {
41.                        s[l] = (c[l] + input[j] * output[k]) % 10;  
42.                        c[l +1] = (c[l] + input[j] * output[k]) / 10;   
43.                        temp[l] += s[l];    
44.                        l ++;
45.                    }
46.                    if(c[l] != 0)
47.                    {
48.                        temp[l] = c[l];
49.                        l = l + 1;
50.                    }
51.                    m = l;
52.                }
53.                out = m;
54.                inttempc[2000] = {0};
55.                for(m = 0; m < out; m ++)
56.                {
57.                    output[m] = (temp[m] + tempc[m]) % 10;  
58.                    tempc[m +1] = (temp[m] + tempc[m]) / 10;    
59.                }
60.                if(tempc[m] != 0)
61.                {
62.                    output[m] = tempc[m];
63.                    out = out + 1;
64.                }
65.                memset(temp, 0, sizeof(temp));//将temp清零;
66.            }
67.        }
68.        if(out <= 6)//总位数<=6, >6, 倒序输出;输出时,竟然还不能以零开头!!!
69.        {
70.            for(i = out - 1; i >= 0; i --)
71.                printf("%d", output[i]);
72.        }
73.        else
74.        {
75.            for(i = 5; i >= 0; i --)
76.            {
77.                 if(output[i] != 0)
78.                     break;
79.            }
80.            for(j = i; j >= 0; j --)
81.                printf("%d", output[j]);
82.        }
83.        printf("\n");
84.    }
85.    return0;
86.}


你可能感兴趣的:(NYOJ 225题 小明求素数积)