is there any way to convert this to a recursion form?
how to find the unknown prime factors(in case it is a semiprime)?
semiPrime function:
bool Recursividad::semiPrimo(int x)
{
int valor = 0;
bool semiPrimo = false;
if(x < 4)
{
return semiPrimo;
}
else if(x % 2 == 0)
{
valor = x / 2;
if(isPrime(valor))
{
semiPrimo = true;
}
}
return semiPrimo;
}
Edit: i’ve come to a partial solution(not in recursive form). i know i have to use tail recursion but where?
bool Recursividad::semiPrimo(int x){
bool semiPrimo=false;
vector<int> listaFactores= factorizarInt(x);
vector<int> listaFactoresPrimos;
int y = 1;
for (vector<int>::iterator it = listaFactores.begin();
it!=listaFactores.end(); ++it) {
if(esPrimo(*it)==true){
listaFactoresPrimos.push_back(*it);
}
}
int t=listaFactoresPrimos.front();
if(listaFactoresPrimos.size()<=1){
if(t*t==x){
semiPrimo=true;
}
}else{
int f=0;
#pragma omp parallel
{
#pragma omp for
for (vector<int>::iterator it = listaFactoresPrimos.begin();
it!=listaFactoresPrimos.end(); ++it) {
f=*it;
int j=0;
for (vector<int>::iterator ot = listaFactoresPrimos.begin();
ot!=listaFactoresPrimos.end(); ++ot) {
j=*ot;
if((f * j)==x){
semiPrimo=true; }
}
}
}
}
return semiPrimo;
}
any help would be appreciated
You can convert a loop into recursion in a formulaic manner. Note that
do_something()needn’t be a single function call; it can be anything (except flow control likebreakthat’d change the loop behavior):becomes
Note also that you can rewrite that as the following, which in a good compiler will actually run just as fast as the iterative version (this is called “tail-call optimization”). gcc 4.6.2, for example, manages to do this—actually, its smart enough to do the above version as well.