1. 程式人生 > 實用技巧 >試題 演算法訓練 Torry的困惑(基本型)

試題 演算法訓練 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 }