Program for Mobius Function
Last Updated :
20 Jan, 2025
Mobius Function \mu(n) is a multiplicative function that is used in combinatorics. It has one of three possible values -1, 0 and 1.
For any positive integer n, \mu(n) = \begin{cases} 1, & \text{ if } n=1, \\ 0, & \text{ if } a^2 \mid n \text{ for some } a > 1 \text{ (i.e., } n \text{ has a squared prime factor)}, \\ (-1)^k, & \text { if } n \text{ is the product of } k \text{ distinct primes.} \end{cases}
Examples:
Input : 6
Output : 1
Solution: Prime Factors: 2 3.
Therefore p = 2, (-1)^p = 1
Input: 49
Output: 0
Solution: Prime Factors: 7 ( occurs twice).
Since the prime factor occurs twice answer
is 0.
Input: 3
Output: -1
Solution: Prime Factors: 3. Therefore p = 1,
(-1) ^ p =-1
Input : 78
Output : 1
Solution: Prime Factors: 3, 13. Therefore p = 2,
(-1)^p = 1
Method 1 (Simple)
We iterate through all numbers i smaller than or equal to N. For every number we check if it divides N. If yes, we check if it's also prime. If both conditions are satisfied, we check if its square also divides N. If yes, we return 0. If the square doesn't divide, we increment count of prime factors. Finally, we return 1 if there are an even number of prime factors and return -1 if there are odd number of prime factors.
C++
// CPP Program to evaluate Mobius Function
// M(N) = 1 if N = 1
// M(N) = 0 if any prime factor of N is contained twice
// M(N) = (-1)^(no of distinct prime factors)
#include<iostream>
using namespace std;
// Function to check if n is prime or not
bool isPrime(int n)
{
if (n < 2)
return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
int mobius(int N)
{
// Base Case
if (N == 1)
return 1;
// For a prime factor i check if i^2 is also
// a factor.
int p = 0;
for (int 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 Functions M(N) at N = " << N << " is: "
<< mobius(N) << endl;
cout << "Mobius Functions M(N) at N = " << 25 << " is: "
<< mobius(25) << endl;
cout << "Mobius Functions M(N) at N = " << 6 << " is: "
<< mobius(6) << endl;
}
Java
// Java program for mobius function
import java.io.*;
public class GFG {
// C# Program to evaluate Mobius
// Function: M(N) = 1 if N = 1
// M(N) = 0 if any prime factor
// of N is contained twice
// M(N) = (-1)^(no of distinct
// prime factors)
// Function to check if n is
// prime or not
static boolean isPrime(int n)
{
if (n < 2)
return false;
for (int i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
static int mobius(int N)
{
// Base Case
if (N == 1)
return 1;
// For a prime factor i check if
// i^2 is also a factor.
int p = 0;
for (int 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
static public void main(String[] args)
{
int N = 17;
System.out.println("Mobius Functions M(N) at " +
" N = " + N + " is: " + mobius(N));
System.out.println("Mobius Functions M(N) at " +
" N = " + 25 + " is: " + mobius(25));
System.out.println("Mobius Functions M(N) at " +
" N = " + 6 + " is: " + mobius(6));
}
}
// This code is contributed by vt_m
Python3
# Python Program to
# evaluate Mobius def
# M(N) = 1 if N = 1
# M(N) = 0 if any
# prime factor of
# N is contained twice
# M(N) = (-1)^(no of
# distinct prime factors)
# def to check if
# n is prime or not
def isPrime(n) :
if (n < 2) :
return False
for i in range(2, n + 1) :
if (i * i <= n and n % i == 0) :
return False
return True
def mobius(N) :
# Base Case
if (N == 1) :
return 1
# For a prime factor i
# check if i^2 is also
# a factor.
p = 0
for i in range(1, N + 1) :
if (N % i == 0 and
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 = p + 1
# All prime factors are
# contained only once
# Return 1 if p is even
# else -1
if(p % 2 != 0) :
return -1
else :
return 1
# Driver Code
N = 17
print ("Mobius defs M(N) at N = {} is: {}" .
format(N, mobius(N)),end = "\n")
print ("Mobius defs M(N) at N = {} is: {}" .
format(25, mobius(25)),end = "\n")
print ("Mobius defs M(N) at N = {} is: {}" .
format(6, mobius(6)),end = "\n")
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
// C# Program to evaluate Mobius Function
using System;
public class GFG
{
// M(N) = 1 if N = 1
// M(N) = 0 if any prime factor
// of N is contained twice
// M(N) = (-1)^(no of distinct
// prime factors)
// Function to check if n is
// prime or not
static bool isPrime(int n)
{
if (n == 2)
return true;
if (n % 2 == 0)
return false;
for (int i = 3; i * i <= n / 2; i += 2)
if (n % i == 0)
return false;
return true;
}
static int mobius(int N)
{
// Base Case
if (N == 1)
return 1;
// For a prime factor i check
// if i^2 is also a factor.
int p = 0;
for (int i = 2; 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
static public void Main()
{
Console.WriteLine("Mobius Functions M(N) at " +
"N = " + 17 + " is: " + mobius(17));
Console.WriteLine("Mobius Functions M(N) at " +
"N = " + 25 + " is: " + mobius(25));
Console.WriteLine("Mobius Functions M(N) at " +
"N = " + 6 + " is: " + mobius(6));
}
}
// This code is contributed by vt_m
JavaScript
<script>
// JavaScript Program to evaluate Mobius
// Function: M(N) = 1 if N = 1
// M(N) = 0 if any prime factor
// of N is contained twice
// M(N) = (-1)^(no of distinct
// prime factors)
// Function to check if n is
// prime or not
function isPrime(n)
{
if (n < 2)
return false;
for (let i = 2; i * i <= n; i++)
if (n % i == 0)
return false;
return true;
}
function mobius(N)
{
// Base Case
if (N == 1)
return 1;
// For a prime factor i check if
// i^2 is also a factor.
let p = 0;
for (let 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
let N = 17;
document.write("Mobius Functions M(N) at " +
" N = " + N + " is: " + mobius(N) + "<br/>");
document.write("Mobius Functions M(N) at " +
" N = " + 25 + " is: " + mobius(25) + "<br/>");
document.write("Mobius Functions M(N) at " +
" N = " + 6 + " is: " + mobius(6) + "<br/>");
</script>
PHP
<?php
// PHP Program to evaluate Mobius Function
// M(N) = 1 if N = 1
// M(N) = 0 if any prime factor of
// N is contained twice
// M(N) = (-1)^(no of distinct prime factors)
// Function to check if n is prime or not
function isPrime($n)
{
if ($n < 2)
return false;
for ($i = 2; $i * $i <= $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
function mobius($N)
{
// Base Case
if ($N == 1)
return 1;
// For a prime factor i
// check if i^2 is also
// a factor.
$p = 0;
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
$N = 17;
echo "Mobius Functions M(N) at N = " ,$N , " is: "
, mobius($N) ,"\n";
echo "Mobius Functions M(N) at N = " ,25, " is: "
, mobius(25),"\n" ;
echo "Mobius Functions M(N) at N = " ,6, " is: "
, mobius(6) ;
// This code is contributed by nitin mittal.
?>
Output:
Mobius Functions M(N) at N = 17 is: -1
Mobius Functions M(N) at N = 25 is: 0
Mobius Functions M(N) at N = 6 is: 1
Time Complexity: O(n?n )
Auxiliary Space: O(1)
Method 2 (Efficient)
The idea is based on efficient program to print all prime factors of a given number. The interesting thing is, we do not need inner while loop here because if a number divides more than once, we can immediately return 0.
C++
// Program to print all prime factors
# include <bits/stdc++.h>
using namespace std;
// Returns value of mobius()
int mobius(int n)
{
int p = 0;
// Handling 2 separately
if (n%2 == 0)
{
n = n/2;
p++;
// If 2^2 also divides N
if (n % 2 == 0)
return 0;
}
// Check for all other prime factors
for (int i = 3; i <= sqrt(n); i = i+2)
{
// If i divides n
if (n%i == 0)
{
n = n/i;
p++;
// If i^2 also divides N
if (n % i == 0)
return 0;
}
}
return (p % 2 == 0)? -1 : 1;
}
// Driver code
int main()
{
int N = 17;
cout << "Mobius Functions M(N) at N = " << N << " is: "
<< mobius(N) << endl;
cout << "Mobius Functions M(N) at N = " << 25 << " is: "
<< mobius(25) << endl;
cout << "Mobius Functions M(N) at N = " << 6 << " is: "
<< mobius(6) << endl;
}
Java
// Java program to print all prime factors
import java.io.*;
class GFG {
// Returns value of mobius()
static int mobius(int n)
{
int p = 0;
// Handling 2 separately
if (n % 2 == 0)
{
n = n / 2;
p++;
// If 2^2 also divides N
if (n % 2 == 0)
return 0;
}
// Check for all other prime factors
for (int i = 3; i <= Math.sqrt(n);
i = i+2)
{
// If i divides n
if (n % i == 0)
{
n = n / i;
p++;
// If i^2 also divides N
if (n % i == 0)
return 0;
}
}
return (p % 2 == 0)? -1 : 1;
}
// Driver code
public static void main (String[] args)
{
int N = 17;
System.out.println( "Mobius Functions"
+ " M(N) at N = " + N + " is: "
+ mobius(N));
System.out.println ("Mobius Functions"
+ "M(N) at N = " + 25 + " is: "
+ mobius(25));
System.out.println( "Mobius Functions"
+ "M(N) at N = " + 6 + " is: "
+ mobius(6));
}
}
// This code is contributed by anuj_67.
Python3
# Python Program to evaluate
# Mobius def M(N) = 1 if N = 1
# M(N) = 0 if any prime factor
# of N is contained twice
# M(N) = (-1)^(no of distinct
# prime factors)
import math
# def to check if n
# is prime or not
def isPrime(n) :
if (n < 2) :
return False
for i in range(2, n + 1) :
if (n % i == 0) :
return False
i = i * i
return True
def mobius(n) :
p = 0
# Handling 2 separately
if (n % 2 == 0) :
n = int(n / 2)
p = p + 1
# If 2^2 also
# divides N
if (n % 2 == 0) :
return 0
# Check for all
# other prime factors
for i in range(3, int(math.sqrt(n)) + 1) :
# If i divides n
if (n % i == 0) :
n = int(n / i)
p = p + 1
# If i^2 also
# divides N
if (n % i == 0) :
return 0
i = i + 2
if(p % 2 == 0) :
return -1
else :
return 1
# Driver Code
N = 17
print ("Mobius defs M(N) at N = {} is: {}\n" .
format(N, mobius(N)));
print ("Mobius defs M(N) at N = 25 is: {}\n" .
format(mobius(25)));
print ("Mobius defs M(N) at N = 6 is: {}\n" .
format(mobius(6)));
# This code is contributed by
# Manish Shaw(manishshaw1)
C#
// C# program to print all prime factors
using System;
class GFG {
// Returns value of mobius()
static int mobius(int n)
{
int p = 0;
// Handling 2 separately
if (n % 2 == 0)
{
n = n / 2;
p++;
// If 2^2 also divides N
if (n % 2 == 0)
return 0;
}
// Check for all other prime factors
for (int i = 3; i <= Math.Sqrt(n);
i = i+2)
{
// If i divides n
if (n % i == 0)
{
n = n / i;
p++;
// If i^2 also divides N
if (n % i == 0)
return 0;
}
}
return (p % 2 == 0)? -1 : 1;
}
// Driver Code
public static void Main ()
{
int N = 17;
Console.WriteLine( "Mobius Functions"
+ " M(N) at N = " + N + " is: "
+ mobius(N));
Console.WriteLine("Mobius Functions"
+ "M(N) at N = " + 25 + " is: "
+ mobius(25));
Console.WriteLine( "Mobius Functions"
+ "M(N) at N = " + 6 + " is: "
+ mobius(6));
}
}
// This code is contributed by anuj_67.
JavaScript
<script>
// JavaScript program to print all prime factors
// Returns value of mobius()
function mobius(n)
{
let p = 0;
// Handling 2 separately
if (n % 2 == 0)
{
n = parseInt(n / 2, 10);
p++;
// If 2^2 also divides N
if (n % 2 == 0)
return 0;
}
// Check for all other prime factors
for (let i = 3; i <= Math.sqrt(n); i = i+2)
{
// If i divides n
if (n % i == 0)
{
n = parseInt(n / i, 10);
p++;
// If i^2 also divides N
if (n % i == 0)
return 0;
}
}
return (p % 2 == 0)? -1 : 1;
}
let N = 17;
document.write( "Mobius Functions"
+ " M(N) at N = " + N + " is: "
+ mobius(N) + "</br>");
document.write("Mobius Functions"
+ "M(N) at N = " + 25 + " is: "
+ mobius(25) + "</br>");
document.write( "Mobius Functions"
+ "M(N) at N = " + 6 + " is: "
+ mobius(6));
</script>
PHP
<?php
// PHP Program to print
// all prime factors
// Returns value of mobius()
function mobius( $n)
{
$p = 0;
// Handling 2 separately
if ($n % 2 == 0)
{
$n = $n / 2;
$p++;
// If 2^2 also divides N
if ($n % 2 == 0)
return 0;
}
// Check for all
// other prime factors
for ( $i = 3; $i <= sqrt($n); $i = $i + 2)
{
// If i divides n
if ($n % $i == 0)
{
$n = $n / $i;
$p++;
// If i^2 also divides N
if ($n % $i == 0)
return 0;
}
}
return ($p % 2 == 0)? -1 : 1;
}
// Driver code
$N = 17;
echo "Mobius Functions M(N) at N = ", $N, " is: "
, mobius($N),"\n" ;
echo "Mobius Functions M(N) at N = " , 25 , " is: "
, mobius(25),"\n";
echo "Mobius Functions M(N) at N = " , 6 , " is: "
, mobius(6) ;
// This code is contributed by anuj_67.
?>
Output:
Mobius Functions M(N) at N = 17 is: -1
Mobius Functions M(N) at N = 25 is: 0
Mobius Functions M(N) at N = 6 is: 1
Time Complexity: O(?n)
Auxiliary Space: O(1)
Please suggest if someone has a better solution which is more efficient in terms of space and time.
References
1) https://mathworld.wolfram.com/MobiusFunction.html
2) https://en.wikipedia.org/wiki/M%C3%B6bius_function
3) https://en.wikipedia.org/wiki/Completely_multiplicative_function
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem