NOJ [1300] Factor

来源:互联网 发布:百度派 知乎 编辑:程序博客网 时间:2024/06/08 12:15
链接地址:http://ac.nbutoj.com/Problem/view.xhtml?id=1300

死月很喜欢讲故事, 这次他讲了一个又恐怖又搞笑又悲伤的故事.
从前, 有一只僵尸, 他放了一个屁, 最后死了.
言归正传, 此题就是让你将一个数的所有因数都输出, 1不用输出.
那么我们只要将这个数先一直对2除, 然后一直对3除, 然后...直到这个数变为1为止, 那么就完成了. 结果, 超时.
原因 : x(1 < x < 2^63).
所以,再想想。当这个数已经对2求完了, 那么就不可能对2的整数倍求了, 所以我们从3开始的时候, i += 2. 步长从1变为了2. 节约了很多时间,但是这个还是不够的。
我们可以试想一下,当一个数N, 他能整除X, 那么他一定能整除(N / X).
然后,一个数最小能整除的数是2, 那么当i步长到大于N / 2的时候, 那么一定是找不到因数的了(想一想为什么). 所以,结束条件, 从O(n)的时间就变成了O(sqrt(n))的时间了.

以下是我出题的代码。

#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
int p = 0;
__int64 x;
//freopen("data.in", "r", stdin);
//freopen("data.out", "w", stdout);

while (~scanf("%I64d", &x))
{
if (x == -1) break;
while (x % 2 == 0)
{
printf("2\n");
x /= 2;
}
__int64 y = 3;
for (;y <= (__int64)sqrt(x * 1.0);)
{
if (x % y == 0)
{
printf("%I64d\n", y);
x /= y;
}
else y += 2;
}
if (x != 1) printf("%I64d\n", x);
printf("\n");
}

return 0;
}

0 0
原创粉丝点击