HDU Largest prime factor(埃拉托色尼篩選法求素數模板法改動)
阿新 • • 發佈:2019-01-31
題意:給你一個數,求它這個數的最大素因子在素數表的第幾位
思路:剛開始思路有一點錯誤,看錯誤程式碼
錯誤程式碼:
AC程式碼1:#include <iostream>0 #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> typedef long long ll; using namespace std; const int maxn = 1e6+10; int isprime[maxn]; void init() { int i,j; int nprime = 0; memset(isprime,-1,sizeof(isprime)); isprime[1] = 0; for(i=2; i<maxn; i++)//剛開始程式老是崩潰,後來開小就不會崩潰,但實際上我覺得應該開到maxn,AC的程式也開到了maxn { if(isprime[i] == -1) { nprime++; isprime[i] = nprime; for(j=i*i; j<maxn; j+=i)//這裡和打素數表有一點不同不是從i*i開始的,要是這樣寫程式會奔潰, { isprime[j] = nprime; } } } } int main() { int n; init(); while(scanf("%d",&n) != EOF) { printf("%d\n",isprime[n]); } return 0; }
AC程式碼2:#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <queue> #include <stack> #include <map> #include <cstring> #include <climits> #include <cmath> #include <cctype> typedef long long ll; using namespace std; const int maxn = 1e6+10; int isprime[maxn]; void init() { int i,j; int nprime = 0; memset(isprime,-1,sizeof(isprime)); isprime[1] = 0; for(i=2; i<maxn; i++) { if(isprime[i] == -1) { nprime++; for(j=i; j<maxn; j+=i) { isprime[j] = nprime; } } } } int main() { int n; init(); while(scanf("%d",&n) != EOF) { printf("%d\n",isprime[n]); } return 0; }
#include<stdio.h> int a[1000000]={0}; int main() { int i,j,l=0,n; a[1]=0; for(i=2;i<1000000;i++) { if(!a[i]) { l++; for(j=i;j<1000000;j+=i) { a[j]=l; } } } while(scanf("%d",&n)!=EOF) { printf("%d\n",a[n]); } return 0; }
程式更簡潔