欧拉函数代码以及例题(Calculation 2)

本文详细解析了欧拉函数的概念及其计算方法,提供了实用的代码实现,并通过一道具体题目阐述如何利用欧拉函数解决数论问题,如求解小于N的所有不与N互质的数的和。

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

关于欧拉函数,感谢大佬分享:https://blog.youkuaiyun.com/ydd97/article/details/47805419

先讲欧拉函数:

欧拉函数就是指:对于一个正整数n,小于n且和n互质的正整数(包括1)的个数,记作φ(n) 。

欧拉函数的通式:φ(n)=n*(1-1/p1)*(1-1/p2)*(1-1/p3)*(1-1/p4)…..(1-1/pn),其中p1, p2……pn为n的所有质因数,n是不为0的整数。φ(1)=1(唯一和1互质的数就是1本身)。

对于上述的通式一定要牢记在心,因为这是计算欧拉函数最重要的一步。  切记切记~~~~
代码:

int phi(int n){//求欧拉函数的代码 
	int ans=n;
	for(int i=2;i*i<=n;i++){
		if(n%i==0){//如果是n的质因子
			ans-=ans/i;//模拟欧拉函数通式
			while(n%i==0)n/=i;//在欧拉函数中每个质因子只用一下
		}
	}	
	if(n>1)ans-=ans/n;//如果N不是1,那么n一定也是一个质因子
	return ans;
} 

然后题描述:

Given a positive integer N, your task is to calculate the sum of the positive integers less than N which are not coprime to N. A is said to be coprime to B if A, B share no common positive divisors except 1.

Input

For each test case, there is a line containing a positive integer N(1 ≤ N ≤ 1000000000). A line containing a single 0 follows the last test case.

Output

For each test case, you should print the sum module 1000000007 in a line.

Sample Input

3 4 0

Sample Output

0 2

 

大意就是給一个数,然后求小于这个数的所有和它不互质的数的和。

思路:所有小于它的和,减去小于它的质数的和。

质数之和  N*phi(N)/2    (如果 i 是互质的   那么N-i也是互质的  那么i  +  N- i == N   除以2是因为每个数被算了两遍 )

公式  ans=N*(N-1)/2 - N*phi(N)/2;

代码:

//求小于N的不和N互质的数的和 
#include<bits/stdc++.h>
using namespace std;
int phi(int n){//求欧拉函数的代码 
	int ans=n;
	for(int i=2;i*i<=n;i++){
		if(n%i==0){
			ans-=ans/i;
			while(n%i==0)n/=i;
		}
	}	
	if(n>1)ans-=ans/n;
	return ans;
} 
int main(){
	int t;
	cin>>t;
	while(t){
		cout<<t*(t-1)/2-t*phi(t)/2<<endl;		
		cin>>t;
	}
	return 0;	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值