Skip to content

Instantly share code, notes, and snippets.

@aadipoddar
Created February 1, 2022 06:51
Show Gist options
  • Save aadipoddar/2ecfa3347e027f7b9ea77ca555399a9b to your computer and use it in GitHub Desktop.
Save aadipoddar/2ecfa3347e027f7b9ea77ca555399a9b to your computer and use it in GitHub Desktop.
Program To Find Mobius Function
/*
A MOBIUS function M(N) returns the value -1 or 0 or 1 fora natural number (N) by
the following conditions are defined :
When,
M(N) =1 if N=1.
M(N) =0 if any prime factor of N is contained more than once.
M(N) =(-1)^P if N is the product of ‘P’ distinct prime factors.
Write a program to accept a positive natural number (N) and display the MOBIUS result
with proper message.
Design your program which will enable the output in the format given below:
Sample 1
INPUT: 78
OUTPUT: 78 =2x3x13
NUMBER OF DISTINCT PRIME FACTORS = 3
M(78) = -1
Sample 2
INPUT: 34
OUTPUT: 34 =2x17
NUMBER OF DISTINCT PRIME FACTORS = 2
M(34) =1
Sample 3
INPUT: 12
OUTPUT: 12 =2x2x3
DUPLICATE PRIME FACTORS
M(12) = 0
Sample 4
INPUT: 1
OUTPUT: 1=1
NO PRIME FACTORS
M(1) =1
*/
import java.util.*;
class MobiusNumber {
int Mobius(int n) {
if (n == 1)
return 1;
else {
boolean duplicate = false;
int N = n;
for (int i = 2; i < n; i++) {
int count = 0;
while (n % i == 0) {
count++;
n = n / i;
}
if (count > 1) {
duplicate = true;
return 0;
}
}
if (duplicate == false)
return MobiusNotDuplicate(N);
return -2;
}
}
int MobiusNotDuplicate(int n) {
int count = 0;
int N = n;
for (int i = 2; i < N; i++) {
if (n % i == 0) {
count++;
n /= i;
}
}
return (int) Math.pow(-1, count);
}
public static void main() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int number = sc.nextInt();
MobiusNumber m = new MobiusNumber();
int result = m.Mobius(number);
System.out.println("The mobius number is " + result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment