找质数

Program for Mobius Function
Given an integer N. The task is to find Mobius function of all numbers from 1 to N.
https://www.geeksforgeeks.org/program-for-mobius-function-set-2/
Input: N = 5
Output: 1 -1 -1 0 -1
Input: N = 10
Output: 1 -1 -1 0 -1 1 -1 0 0 1
合数:-1,1:1,质数:0

// C++ implementation of the approach 
#include <bits/stdc++.h> 
using namespace std; 
#define N 100005 

int lpf[N]; 

// Function to calculate least 
// prime factor of each number 
void least_prime_factor() 
{ 
	for (int i = 2; i < N; i++) 

		// If it is a prime number 
		if (!lpf[i]) 

			for (int j = i; j < N; j += i) 

				// For all multiples which are not 
				// visited yet. 
				if (!lpf[j]) 
					lpf[j] = i; 
} 

// Function to find the value of Mobius function 
// for all the numbers from 1 to n 
void Mobius(int n) 
{ 
	// To store the values of Mobius function 
	int mobius[N]; 

	for (int i = 1; i < N; i++) { 

		// If number is one 
		if (i == 1) 
			mobius[i] = 1; 
		else { 

			// If number has a squared prime factor 
			if (lpf[i / lpf[i]] == lpf[i]) 
				mobius[i] = 0; 

			// Multiply -1 with the previous number 
			else
				mobius[i] = -1 * mobius[i / lpf[i]]; 
		} 
	} 

	for (int i = 1; i <= n; i++) 
		cout << mobius[i] << " "; 
} 

// Driver code 
int main() 
{ 
	int n = 5; 

	// Function to find least prime factor 
	least_prime_factor(); 

	// Function to find mobius function 
	Mobius(n); 
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值