Question
*10.5 (Displaying the prime factors) Write a program that prompts the user to enter a positive integer and displays all its smallest factors in decreasing
*10.5 (Displaying the prime factors) Write a program that prompts the user to enter a positive integer and displays all its smallest factors in decreasing order. For example, if the integer is 120, the smallest factors are displayed as 5, 3, 2, 2 2. Use the StackofIntegers class to store the factors (e.g., 2, 2, 2, 3, 5) and retrieve and display them in reverse order.
Here is my code. My output keeps displaying 5 instead of a list of prime factors. Please correct.
import java.util.Scanner; public class StackOfIntegers { //declare variables private int[] a; private int size; //Constructor with default array size 16 public StackOfIntegers(int capacity){ a = new int [capacity]; } //This will push a new integer to the top of the stack public int push (int num){ if (size >= a.length){ int [] temp = new int[a.length * 2]; System.arraycopy(a, 0, temp, 0 , a.length); a = temp; } return a[size++] = num; } //Return and remove the top element from the stack public int pop(){ return a[--size]; } //Return the top elements from the stack public int peek(){ return a[size - 1]; } //Test to see if the stack is empty public boolean empty(){ return size == 0; } //Return the number of elements in the stack public int getSize(){ return size; } }
import java.util.Scanner; public class StackTest { public static void main(String[] args){ //create an object to access StackOfIntegers class StackOfIntegers test = new StackOfIntegers(); int count = 0; Scanner input = new Scanner(System.in); /*prompt the user to enter an integer and display the prime factors of the given number */ System.out.println("Enter an integer: "); int num = input.nextInt(); System.out.println("The prime factors for the given number " + num + " is: "); int factor = 2; //the loop will find the prime numbers while(factor <= num){ if(num % factor == 0){ num = num / factor; test.push(factor); count++; }else{ factor++; } } //display the prime numbers for(int i = 0; i <= count; i++); System.out.print(test.pop() + " "); } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started