试题 算法训练 Torry的困惑(基本型)

资源限制
时间限制:1.0s   内存限制:512.0MB
 
问题描述
  Torry从小喜爱数学。一天,老师告诉他,像2、3、5、7……这样的数叫做质数。Torry突然想到一个问题,前10、100、1000、10000……个质数的乘积是多少呢?他把这个问题告诉老师。老师愣住了,一时回答不出来。于是Torry求助于会编程的你,请你算出前n个质数的乘积。不过,考虑到你才接触编程不久,Torry只要你算出这个数模上50000的值。
 
输入格式
  仅包含一个正整数n,其中n<=100000。
 
输出格式
  输出一行,即前n个质数的乘积模50000的值。
 
样例输入
1

样例输出

2

 

这题我们可以先筛选素数并进行标记,然后将前n个素数相乘取模,最后输出答案即可.

 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <string>
 6 #include <cmath>
 7 #include <algorithm>
 8 #define INF 0x3f3f3f3f
 9 #define zero 1e-7
10 
11 using namespace std;
12 typedef long long ll;
13 const ll mod=50000;
14 const ll max_n=1e6;
15 int p[max_n]={0};//标记是否为素数,初始化为0-是素数 
16 int n;
17 
18 void judge() {
19     for(int i=2; i<max_n; i++) {
20         if(!p[i]) {//当前下标i是素数 
21             for(int j=i*2; j<max_n; j+=i) {
22                 p[j]=1;
23             }
24         }
25     }
26 }
27 
28 int main() {
29     judge();
30     cin>>n;
31     int cnt=0, ans=1;
32     for(int i=2; i<max_n; i++) {
33         if(!p[i]) {
34             cnt++;
35             ans=ans*i%mod;
36             if(cnt==n) break;
37          }
38     }
39     printf("%d", ans);
40     return 0;
41 }
原文地址:https://www.cnblogs.com/wwqzbl/p/13534825.html