Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

这题用素筛最简单,找最大素因子的时间复杂度是O(1)

Posted by Eov_Second at 2016-12-16 10:49:33 on Problem 3048
大家平时筛的时候通常是用0,1去标记合数,即每次筛出合数,就在其对应数组里标1。最后剩下0的就是素数。其实稍微改进一下,用k去筛k的倍数时候,不是标1,而是标k,那么数组里对应的数到最后就是该数的最大质因数。

关键代码(仅供示意)
1.数组做标记,先让每个数素因子等于其本身
for(i=2;i<20001;i++)a[i]=i;

2.从2开始筛,2的倍数,数组改为2;3的倍数改为3...依此类推
for(i=2;i<20001;i++)
{
  if(a[i]==i)//对应数组元素等于自身的肯定是素数
  {
    for(j=2*i;j<20001;j+=i)
      a[j]=i;
  }  
}

3.对于任意整数k,a[k]对应的值就是其最大素因数

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator