Skip to content

Instantly share code, notes, and snippets.

@mariack
Last active August 29, 2015 14:19
Show Gist options
  • Save mariack/fe457b5fa1cfb255a5f4 to your computer and use it in GitHub Desktop.
Save mariack/fe457b5fa1cfb255a5f4 to your computer and use it in GitHub Desktop.
/**
* Maria Kalusz
* Lab 11 - Prime Factorization
* April 17, 2015
*/
package Assignments;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class FactorGenerator
{
public boolean hasMoreFactors(int y)
{
if (y == 1)
{
return false;
}
else
return true;
}
public List nextFactor(int num)
{
int i;
FactorGenerator x = new FactorGenerator();
List<Integer> factors = new ArrayList<Integer>();
for(i = 2; i < num + 1; i++)
{
while(num % i == 0)
{
factors.add(i);
num/=i;
x.hasMoreFactors(num - i);
x.isPrime(i);
}
}
return factors;
}
private boolean isPrime(int n)
{
if (n <= 3)
{
return n > 1;
}
else if (n % 2 == 0 || n % 3 == 0)
{
return false;
}
else
{
double sqrtN = Math.floor(Math.sqrt(n));
for (int i = 5; i <= sqrtN; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0)
{
return false;
}
}
}
return true;
}
public static void main(String[] args)
{
int x;
List y;
Scanner keyboard;
FactorGenerator factors = new FactorGenerator();
System.out.print("Enter a positive integer to be factored: ");
keyboard = new Scanner(System.in);
x = keyboard.nextInt();
while (x < 1)
{
System.out.println("Sorry, zero and negative numbers are not allowed.");
System.out.print("Enter a positive integer to be factored: ");
keyboard = new Scanner(System.in);
x = keyboard.nextInt();
}
y = factors.nextFactor(x);
System.out.printf("The factors of %d are: ", x);
System.out.println(y);
}
}
/**
* Maria Kalusz
* Lab 11 - Prime Factorization
* April 17, 2015
*/
package Assignments;
import java.util.List;
import java.util.ArrayList;
public class FactorGenerator
{
public List factorGenerator(int num)
{
int i;
List<Integer> factors = new ArrayList<Integer>();
for(i = 2; i < num + 1; i++)
{
while(num % i == 0)
{
factors.add(i);
num/=i;
}
}
return factors;
}
public static void main(String[] args)
{
FactorGenerator facts = new FactorGenerator();
List y;
y = facts.factorGenerator(350);
System.out.println("Factors in list are: " + y);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment