• November 11th, 2010, 05:54 PM
uks2h
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.");   } }```
• November 11th, 2010, 06:26 PM
javapenguin
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.
• November 11th, 2010, 06:29 PM
javapenguin
Why are you using another username?

http://www.javaprogrammingforums.com...lp-factor.html
• November 11th, 2010, 06:40 PM
uks2h
Quote:

Originally Posted by javapenguin
Why are you using another username?

http://www.javaprogrammingforums.com...lp-factor.html

??? I'm new to this site. Only have this username.
• November 11th, 2010, 07:20 PM
aussiemcgr
```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)); }```