Trying to write Factoring Numbers Code--Please Help.
I am trying to finish the code for a simple program that will break a number down and give you the factors of that number. I have the program working all for one part. Right now it returns something like "2*2*2*5*5*" and instead I want it to say 2^3+5^2. Can anyone tell me what I would need to have to do this? I need to use some type of loop I think, and a While statement maybe?
Code Java:
import java.util.*;
class Factor
{
String factor(int n)
{
String S = "";
int f = 2;
while (n > 1)
if (n%f == 0)
{
S += f + "*";
n /= f;
}
else
f++;
return S;
}
public void setN(int n)
{
n = 0;
}
public void getN(int n)
{
}
}
class FactorDemo // main Class
{
public static void main(String [] args)
{
Scanner in = new Scanner(System.in);
Factor ML = new Factor();
System.out.print("Enter a positive integer(-1 to stop):");
int n = in.nextInt();
while (n > 0) //0 or negative number to stop the program
// is called a sentinel
{
System.out.println(ML.factor(n));
System.out.print("Enter a positive integer(-1 to stop):");
n = in.nextInt();
}
System.out.println("Thanks for using my program.");
}
}
Re: Trying to write Factoring Numbers Code--Please Help.
You could, but you'd have to test to see if each factor is prime. If it isn't, then it can be simplified.
Beyond that, I've no clue what to do.
Using charAt() won't work as you could have an 11 as a factor.
Re: Trying to write Factoring Numbers Code--Please Help.
Re: Trying to write Factoring Numbers Code--Please Help.
Quote:
Originally Posted by
javapenguin
??? I'm new to this site. Only have this username.
Re: Trying to write Factoring Numbers Code--Please Help.
You want to make some sort of int array in your factor method. Then use that int array to determine how many instances of x number appears. I would advise a List (such as a Vector) since you will not need to worry about size. Here is what you need:
Code java:
String factor(int n)
{
String s;
//Create Integer Vector
Vector<Integer> numbers = new Vector<Integer>();
int f = 2;
while (n > 1)
{
if (n%f == 0)
{
//Add number to Integer Vector
numbers.add(new Integer(f));
n /= f;
}
else
f++;
}
//Go through Vector. Doing this way because we will remove from the list as we go
while(numbers.size()>0)
{
//Get number and remove it to allow counting
Integer tempNumber = numbers.remove(i);
//Counter Variable
int numberOfTimes = 1;
//I think this works, not entirely sure
while(numbers.indexOf(tempNumber)!=-1)
{
//Remove this number from the Vector
numbers.remove(numbers.indexOf(tempNumber));
//Increment counter
numberOfTimes++;
}
if(numberOfTimes==1)
s+=tempNumber+"*";
else
s+=tempNumber+"^"+numberOfTimes+"*";
}
//Remove the last * symbol
return (S.substring(0,s.length()-1));
}
There is probably a better way, but that is the best I could come up with without putting more effort in. I haven't tested the code, so tell me if it doesnt work.