其他分享
首页 > 其他分享> > UVALive2116 The Mobius Function【筛选法+莫比乌斯函数】

UVALive2116 The Mobius Function【筛选法+莫比乌斯函数】

作者:互联网

The Mobius function M(n) is defined on positive integers as follows:
M(n) = 1 if n is 1.
M(n) = 0 if any prime factor of n is contained in n more than once.
M(n) = (−1)^p if n is the product of p different prime factors.
For example:
M(78) = -1, since 78 = 2 × 3 × 13.
M(34) = 1, since 34 = 2 × 17.
M(45) = 0, since 45 = 3 × 3 × 5.
Given a value for n greater than or equal to 1 and less than or equal to 10000, find the value of M(n).
Input
The input consists of a sequence of positive integer values for n followed by ‘-1’. The integers are preceded and/or followed by whitespace (blanks, tabs, and ends of lines).
Output
For each positive integer n, display the value of n and the value of f(n). Use the format shown in the example below, and leave a blank line between the output for each value of n.
Sample Input
78
34 45
105
1
-1
Sample Output
M(78) = -1
M(34) = 1
M(45) = 0
M(105) = -1
M(1) = 1

Regionals 2000 >> North America - North Central NA

问题链接UVALive2116 The Mobius Function
问题简述:(略)
问题分析
    计算莫比乌斯函数,素数打表是必要的。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVALive2116 The Mobius Function */

#include <bits/stdc++.h>

using namespace std;

const int N = 10000 / 2;
const int SQRTN = sqrt((double) N);
bool prime[N + 1];
int primek[N / 7];

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

    prime[0] = prime[1] = false;
    for(int i = 2; i <= SQRTN; i++) {
        if(prime[i]) {
            for(int j = i * i; j <= N; j += i)  //筛选
                prime[j] = false;
        }
    }

    for(int i = 0, j = 0; i <= N; i++)
        if(prime[i])
            primek[j++] = i;
  }

int mobius(int n) {
    int p = 0;
    if(n == 1) return 1;
    for(int i = 0; n >= primek[i] * primek[i]; i++) {
        if(n % primek[i]) continue;
        n /= primek[i];
        p++;
        if(n % primek[i]) continue;
        return 0;
    }
    if(n != 1) p++;
    return (p % 2) ? -1 : 1;
}

int main()
{
    esieve();

    int n, flag = 0;
    while(~scanf("%d",&n) && n != -1) {
        if(flag)
            printf("\n");
        flag = 1;
        printf("M(%d) = %d\n", n, mobius(n));
    }

    return 0;
}

标签:Function,prime,primek,int,45,value,34,Mobius,UVALive2116
来源: https://www.cnblogs.com/tigerisland45/p/10363811.html