加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-14 04:24:59 所属栏目:大数据 来源:网络整理
导读: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)

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) = %dn",n,mobius(n));
    }

    return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读