Monday 31 July 2017

Java Code to find out the prime factors of an integer

Problem:

Design and implement an algorithm to find out the prime factors of an integer


Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FindThePrimeFactors {

int n;
List<Integer> primeNumbers = new ArrayList<Integer>();
List<Integer> primeFactors = new ArrayList<Integer>();

public static void main(String[] args) {
FindThePrimeFactors findThePrimeFactors = new FindThePrimeFactors();
findThePrimeFactors.getTheNumber();
findThePrimeFactors.findThePrimeFactors();
findThePrimeFactors.printPrimeFactors();
}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
n = scanner.nextInt();
scanner.close();
}

public void findThePrimeFactors(){
for (int i = 2; i <= n; i++) {
            while (n % i == 0) {
                primeFactors.add(i);
                n /= i;
            }
        }
}

public void printPrimeFactors(){
System.out.println("the prime factors are: " + primeFactors);
}
}


Output:

enter the number
12
the prime factors are: [2, 2, 3]


enter the number
147
the prime factors are: [3, 7, 7]

enter the number
17
the prime factors are: [17]


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...