Program for Mobius Function in C++


Given a number n; the task is to find the Mobius function of the number n.

What is Mobius Function?

A Mobius function is number theory function which is defined by

$$\mu(n)\equiv\begin{cases}0\1\(-1)^{k}\end{cases}$$

n=  0 If n has one or more than one repeated factors

n= 1 If n=1

n= (-1)k  If n is product of k distinct prime numbers

Example

Input: N = 17
Output: -1
Explanation: Prime factors: 17, k = 1,
(-1)^k 🠠(-1)^1 = -1

Input: N = 6
Output: 1
Explanation: prime factors: 2 and 3, k = 2
(-1)^k 🠠(-1)^2 = 1

Input: N = 25
Output: 0
Explanation: Prime factor is 5 which occur twice so the answer is 0

Approach we will be using to solve the given problem

  • Take an input N.
  • Iterate i from 1 to less than N check the divisible number of N and check if it is a prime or not.
  • If the both conditions satisfy we will check if the square of the number also divides N then the return 0.
  • Else we increment the count of prime factors, if the count number is even then return 1 else if it’s odd return -1.
  • Print the result.

Algorithm

Start
Step 1→ In function bool isPrime(int n)
   Declare i
   If n < 2 then,
      Return false
   Loop For  i = 2 and i * i <= n and i++
      If n % i == 0
         Return false    
      End If
      Return true
Step 2→ In function int mobius(int N)
   Declare i and p = 0
   If N == 1 then,  
      Return 1
   End if
   Loop For  i = 1 and i <= N and i++
      If N % i == 0 && isPrime(i)
         If (N % (i * i) == 0)
            Return 0
         Else
            Increment p by 1
         End if
      End if
   Return (p % 2 != 0)? -1 : 1
Step 3→ In function int main()
   Declare and set N = 17
   Print the results form mobius(N)
Stop

Example

#include<iostream>
using namespace std;
// Function to check if n is prime or not
bool isPrime(int n) {
   int i;
   if (n < 2)
      return false;
   for ( i = 2; i * i <= n; i++)
   if (n % i == 0)
      return false;    
      return true;
}
int mobius(int N) {
   int i;
   int p = 0;
   //if n is 1
   if (N == 1)
   return 1;
   // For a prime factor i check if i^2 is also
   // a factor.
   for ( i = 1; i <= N; i++) {
      if (N % i == 0 && isPrime(i)) {
         // Check if N is divisible by i^2
         if (N % (i * i) == 0)
            return 0;
         else
            // i occurs only once, increase p
            p++;
      }
   }
   // All prime factors are contained only once
   // Return 1 if p is even else -1
   return (p % 2 != 0)? -1 : 1;
}
// Driver code
int main() {
   int N = 17;
   cout  << mobius(N) << endl;
}

Output

N = -1

Updated on: 20-Dec-2019

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements