|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖不欢迎ChatGPT.
本帖不欢迎ChatGPT,我已经问过他了,他也不靠谱
题目 https://www.luogu.com.cn/problem/P1619
记录 https://www.luogu.com.cn/record/123079697
疯狂TLE
我调试了一下,发现xxs算法筛4e8的素数本身就要500ms左右,那留给分解的时间就很少了。
所以这个程序应该怎么优化呢?可以从筛法(虽然好像没法再优化了)或者质因数分解的角度来去优化。
我反正已经没办法了。
源代码
- #include <cstdio>
- #include <cctype>
- #include <vector>
- #include <cstring>
- #include <string>
- #include <algorithm>
- #include <iostream>
- using namespace std;
- #define MAXN 40000000
- vector<int>prime;
- bool is_prime[MAXN];
- inline void itoa(int x,char * str)
- {
- int t=x,i;
- char temp[10]={'\0'};
- for(i=0;t>0;i++)
- {
- temp[i]=t%10+'0';
- t/=10;
- }
- for(int j=i-1;j>-1;j--)
- {
- str[i-j-1]=temp[j];
- }
- str[i]='\0';
- }
- inline int read(void)
- {
- int x=0;
- char ch,flag=0;
- while((ch=getchar())!='\n')
- {
- if(isdigit(ch))
- {
- flag=1;
- x=(x<<3)+(x<<1)+(ch^48);
- }
- if(x>40000000)
- {
- flag=2;
- break;
- }//inf
- }
- if(flag==2)
- {
- while(1)
- {
- if(getchar()=='\n')break;
-
- }
- return -1;
- }
- if(!flag)return -2;//NaN
- return x;
-
- }
- inline string bzfj(int x)
- {
- string ans;
- char str[14]={'\0'};
- int cnt,t=x,p=0;
- while(t>1)
- {
- cnt=0;
- while(t%prime[p]==0)
- {
- t/=prime[p];
- cnt++;
- }
- if(cnt)
- {
- itoa(prime[p],str);
- ans+=str;
- ans+="^";
- itoa(cnt,str);
- ans+=str;
- ans+="*";
- }
- p++;
- }
- ans.pop_back();
-
- return ans;
- }
- int main()
- {
- ios::sync_with_stdio(false);
- cin.tie(0),cout.tie(0);
- int cnt=0;
- int n=MAXN;
- memset(is_prime,true,sizeof(is_prime));
- is_prime[0]=false;
- is_prime[1]=false;
- for(int i=2;i<=n;i++)// init vector
- {
- if(is_prime[i])
- {
- prime.push_back(i);
- cnt++;
- }
- for(int j =0;j<cnt and i*prime[j]<=n;j++)
- {
- is_prime[i*prime[j]]=false;
- if(i%prime[j]==0)break;
- }
- }
- int x;
- while(1)
- {
- cout<<"Enter the number="<<endl;
- x=read();
- if(x==-1)//inf
- cout<<"Prime? No!\nThe number is too large!\n\n";
- else if(x==-2)//NaN
- return 0;
- else
- {
- if(x<2)
- {
- cout<<"Prime? No!"<<endl<<endl;
- continue;
- }
- if(is_prime[x])
- {
- cout<<"Prime? Yes!\n\n";
- }
- else
- {
-
- cout<<"Prime? No!\n"<<x<<"="<<bzfj(x)<<endl<<endl;
- }
- }
- }
-
- }
复制代码
@zhangjinxuan @Ewan-Ahiouy @sfqxx @高山 @元豪
谢谢了! |
|