# Stack Of Integers (to get factors)

• 05-01-2011, 02:42 AM
aramiky818
Stack Of Integers (to get factors)
Hi,
i got the following code which gives the factor.
for example if i type 120
it will give me the factors which are 5 3 2 2 2
the book is now asking to use Stack Of Integers to get reverse as well
so the overall should show
5 3 2 2 2 and 2 2 2 3 5 (when i put in value of 120)
I've been stuck on this for few days now.

public class factors
{
public static void main(String args[])
{
int[] facts = new int[100];
int i = 0, j = 0;
java.util.Scanner input = new java.util.Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = input.nextInt();
System.out.print("The factors for " + number + " is:");
int factor = 2;
while (factor <= number)
{
if (number % factor == 0)
{
number = number / factor;
facts[i] = factor;
i++;
}
else factor++;
}
for (j = i - 1; j >= 0; j--)
{
System.out.print(" " + facts[j]);

}
• 05-01-2011, 02:46 AM
Zack
You have the facts[] array... you could just iterate through it backwards and display each number.

Alternately, you can reverse the array and output it.
• 05-01-2011, 02:49 AM
sunde887
All you should have to do is print the array in the opposite direction.

Code:

```int[] x = {1, 4, 2, 3, 7}; for(int i = 0; i < x.length; ++i){   System.out.print(x[i] + " "); } System.out.println(); for(int i = x.length - 1; i >= 0; --i){   System.out.print(x[i] + " "); }```