Results 1 to 3 of 3
  1. #1
    aramiky818 is offline Member
    Join Date
    Apr 2011
    Posts
    14
    Rep Power
    0

    Default 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]);

    }

  2. #2
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    4

    Default

    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.

  3. #3
    sunde887's Avatar
    sunde887 is offline Moderator
    Join Date
    Jan 2011
    Location
    Richmond, Virginia
    Posts
    3,069
    Blog Entries
    3
    Rep Power
    8

    Default

    All you should have to do is print the array in the opposite direction.

    Java 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] + " ");
    }

Similar Threads

  1. Finding Prime Factors
    By Need Help in forum New To Java
    Replies: 3
    Last Post: 04-09-2011, 01:14 PM
  2. Set of Integers
    By rsjava24 in forum New To Java
    Replies: 7
    Last Post: 01-28-2010, 10:29 AM
  3. Integers and Lists
    By TGH in forum New To Java
    Replies: 8
    Last Post: 01-27-2010, 09:49 AM
  4. how to get the Integers out of a String
    By JordashTalon in forum New To Java
    Replies: 10
    Last Post: 01-30-2009, 06:28 PM
  5. Random Integers
    By www.kwalski.com in forum Java Applets
    Replies: 8
    Last Post: 12-09-2007, 05:49 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •