Reputation: 43
I am making a two classes, the constructing class and the main method where I read a number from a user input and spits out the prime factorizations of the number, code is with Java.
For Example:
Enter Number: 150
5
5
3
2
However, for my program I'm getting the entire list of factors.
Example:
Enter Number: 150
150
75
50
25
5
3
1
How would I change this up to get prime factors?
Main Method:
import java.util.*;
public class FactorPrinter
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a integer: ");
String input1 = scan.nextLine();
int input = Integer.parseInt(input1);
FactorGenerator factor = new FactorGenerator(input);
System.out.print(factor.getNextFactor());
while (!factor.hasMoreFactors())
{
System.out.print(factor.getNextFactor());
}
}
}
Here is my class:
public class FactorGenerator
{
private int num;
private int nextFactor;
public FactorGenerator(int n)
{
num = nextFactor = n;
}
public int getNextFactor()
{
int i = nextFactor - 1 ;
while ((num % i) != 0)
{
i--;
}
nextFactor = i;
return i;
}
public boolean hasMoreFactors()
{
if (nextFactor == 1)
{
return false;
}
else
{
return true;
}
}
}
Upvotes: 0
Views: 1508
Reputation: 313
Following method will print prime factors for a given number. It contains few optimizations as well.
public static void primeFactors(int n) {
if (n <= 1) {
return;
}
while (n % 2 == 0) {
System.out.println(2);
n = n / 2;
}
while (n % 3 == 0) {
System.out.println(3);
n = n / 3;
}
for (int i = 5; i * i <= n; i += 6) {
while (n % i == 0) {
System.out.println(i);
n = n / i;
}
while (n % (i + 2) == 0) {
System.out.println(i + 2);
n = n / (i + 2);
}
}
if (n > 3) {
System.out.println(n);
}
}
Upvotes: 0
Reputation: 310936
A corrected version of @Bohemian's deleted answer:
for (int i = 2; input > 1 && i <= input; i++)
{
if (input % i == 0)
{
System.out.print(i+" ");
do
{
input /= i;
} while (input % i == 0);
}
}
There are much faster algorithms, e.g. Knuth The Art of Computer Programming, Vol I, #4.5.4 algorithm C, which derives from Fermat, but note that there is an important correction on his website. He gives a good testing value as 8616460799L
as it has two rather large prime factors.
Upvotes: 2
Reputation: 1197
You can add a method to check if the factor being returned is a prime factor or not : Try something like this :
public bool isPrime(int number) {
int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return false;
}
return true;
}
And you can use this as :
public class FactorPrinter
{
public static void main(String[] args)
{
//your initial code
while (!factor.hasMoreFactors())
{
int nextFactor= factor.getNextFactor()
if(isPrime(nextFactor))
{
System.out.print();
}
}
}
}
Upvotes: 0