I made a vector stack, with the basic functions (push, pop, peek) and with it I want to do a prime factorization of a value. I did the program, but when I compile it, it stays in an infinite loop that I'm not identifying and does not return anything. Here are the codes:
Stack:
public class Pilha {
public Object[] pilha;
public int posicaoPilha;
public Pilha() {
this.posicaoPilha = -1;
this.pilha = new Object[1000];
}
public boolean isEmpty() {
if (this.posicaoPilha == -1) {
return true;
}
return false;
}
public int size() {
if (this.isEmpty()) {
return 0;
}
return this.posicaoPilha + 1;
}
public Object peek() {
if (this.isEmpty()) {
return null;
}
return this.pilha[this.posicaoPilha];
}
public Object pop() {
if (isEmpty()) {
return null;
}
return this.pilha[this.posicaoPilha--];
}
public void push(Object valor) {
if (this.posicaoPilha < this.pilha.length - 1) {
this.pilha[++posicaoPilha] = valor;
}
}
public void imprime() {
if (isEmpty()) {
System.out.println("Pilha vazia");
}
while (isEmpty() == false) {
System.out.print(pop() + " ");
}
}
}
Primal Factor Function:
public class Exercicio5 {
int fatorPrimo(int n) {
int resultado = 1;
Pilha pilha = new Pilha();
while (n % 2 == 0) {
n = n / 2;
pilha.push(2);
}
for(int i = 3; i <= Math.sqrt(n); i=+ 2) {
while(n % i == 0) {
n = n / i;
pilha.push(i);
}
}
while(!pilha.isEmpty()) {
resultado = resultado * (int)pilha.pop();
}
while(!pilha.isEmpty()) {
System.out.print(pilha.pop() + " * ");
}
return resultado;
}
}
Test Stack:
public class TestaPilha {
public static void main(String args[]) {
Exercicio5 ex5 = new Exercicio5();
int n = 3960;
System.out.println(ex5.fatorPrimo(n));
}
}
Note: Primal factor is to find prime values that are divisors of a n
, which multiplied with each other, result in the value of n
, such as 3960 = 11 * 5 * 3 * 3 * 2 * 2 * 2.