Mobius Function in Java

The Mobius Function M(N) for a natural number N is defined as follows:
M(N) = 1 if N = 1
M(N) = 0 if any prime factor of N is contained in N more than once.
M(N) = -1p if N is a product of p distinct prime factors.

Example:
M(78) = -1 (for 78 = 2 * 3 * 13 and M(78) = -13 = -1).
M(34) = 1 (for 34 = 2 * 17 and M(34) = -12 = 1).
M(12) = 0 (for 12 = 2 * 2 * 3 and M(12) = 0 for 2 appears two times.

Design a class MobiusFn to define Mobius function for a natural number N as follows:
Class name: MobiusFn
Data members/Instance variables:
n: stores an integer number
Member functions:
MobiusFn(): default constructor
void input(): input value of n
int primeFactors(): to check and count prime factors of n
void display(): to find and print values of Mobius Function.

Specify the class MobiusFn giving details of the constructor, int primeFactors() and void display(). Also define the main() function to create an object and call the methods accordingly to enable the task.

import java.io.*;
class MobiusFn{
    private int n;
    public MobiusFn(){
        n = 0;
    }
    public void input()throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("N = ");
        n = Math.abs(Integer.parseInt(br.readLine()));
    }
    public int primeFactors(){
        if(n == 1)
            return 1;
        int count = 0;
        int pf = 2;
        int num = n;
        while(num > 1){
            int x = 0;
            while(num % pf == 0){
                count++;
                x++;
                if(x > 1)
                    return 0;
                num /= pf;
            }
            pf++;
        }
        int result = (int)(Math.pow(-1, count));
        return result;
    }
    public void display(){
        int mf = primeFactors();
        System.out.println("Mobius Function value = " + mf);
    }
    public static void main(String args[])throws IOException{
        MobiusFn obj = new MobiusFn();
        obj.input();
        obj.display();
    }
}

Leave a Reply

%d bloggers like this: