您的位置:首页 > 其它

UVA10699 Count the factors【素数因子个数+筛选法】

2018-02-13 00:02 477 查看
Write a program, that computes the number of different prime factors in a positive integer.
Input
The input tests will consist of a series of positive integers. Each number is on a line on its own. The maximum value is 1000000. The end of the input is reached when the number ‘0’ is met. The number‘0’ shall not be considered as part of the test set.
Output
The program shall output each result on a line by its own, following the format given in the sample output.
Sample Input
289384
930887
692778
636916
747794
238336
885387
760493
516650
641422
0
Sample Output
289384 : 3
930887 : 2
692778 : 5
636916 : 4
747794 : 3
238336 : 3
885387 : 2
760493 : 2
516650 : 3
641422 : 3

问题链接UVA10699 Count the factors

问题简述:(略)
问题分析
  这个问题是计算一个数的素因子个数。
  使用筛选法打表,找出必要的素数备用,计算时间上是节省的。

程序说明
  需要注意循环控制条件。

题记:(略)

参考链接:(略)

AC的C++语言程序如下:/* UVA10699 Count the factors */

#include <bits/stdc++.h>

using namespace std;

const int N = 1e6;
const int SQRTN = ceil(sqrt((double) N));
bool isPrime[N + 1];
int prime[SQRTN + 1], pcount;

// Eratosthenes筛选法
void esieve(void)
{
memset(isPrime, true, sizeof(isPrime));

isPrime[0] = isPrime[1] = false;
pcount = 0;
for(int i=2; i<=SQRTN; i++) {
if(isPrime[i]) {
prime[pcount++] = i;

for(int j=i*i; j<=N; j+=i) //筛选
isPrime[j] = false;
}
}
}

int main()
{
esieve();

int n, cnt, x;
while(cin >> n && n) {
int end = (int)sqrt(n);

cnt = 0;
x = n;
for(int i=0; prime[i]<=end && i < pcount; i++) {
if(x == 0)
break;

if(x % prime[i] == 0) {
cnt++;
do {
x /= prime[i];
} while(x != 1 && x % prime[i] == 0);
}
}
if(x != 1)
cnt++;

printf("%d : %d\n", n, cnt);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: