poj2407

本文介绍了一种计算欧拉函数的有效方法,通过遍历并利用质因数分解,实现了对任意正整数n的欧拉函数φ(n)的计算。该函数表示小于等于n并与n互质的正整数个数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给出n,求欧拉函数,欧拉函数euler(n)表示小于等于n的与n互质的数的个数,在欧拉函数,认为如果两数最大公约数为1,则两数互质。所以,n与1也互质,且euler(1)=1。

分析:计算公式为:φ(x)=x(1-1/p1)(1-1/p2)(1-1/p3)(1-1/p4)…..(1-1/pn),其中p1, p2……pn为x的所有不重复的质因数,x是不为0的整数。

View Code
#include <iostream>
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>
#include
<cmath>
usingnamespace std;

unsigned euler(unsigned x)
{
// 就是公式
unsigned i, res = x;
for (i =2; i < (int) sqrt(x *1.0) +1; i++)
if (x % i ==0)
{
res
= res / i * (i -1);
while (x % i ==0)
x
/= i; // 保证i一定是素数
}
if (x >1)
res
= res / x * (x -1);
return res;
}

int main()
{
//freopen("t.txt", "r", stdin);
int n;
while (scanf("%d", &n), n !=0)
{
printf(
"%d\n", euler(n));
}
return0;
}

转载于:https://www.cnblogs.com/rainydays/archive/2011/05/20/2052132.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值