I am making a program that calculates the prime numbers up to a maximum (20 in the example) and returns the primes, the problem is that my algorithm only returns one number.
#include <cmath>
#include <iostream>
using namespace std;
void mostrar_primos(unsigned long int primos[],unsigned long int tam){
unsigned long int i;
for(i=0;i<tam;i++){
cout<<primos[i]<<endl;
}
}
int main(){ //1000000000
cout<<"Empezando..."<<endl;
unsigned long int maximo = 20; //numero maximo a buscar
//criba secuencial
unsigned long int* primos= new unsigned long int[maximo];//array dinamico
//añadimos el 2 al array para poder saltarnos los pares
primos[0] = 2;
//recorremos los numeros impares desde el 3 hasta maximo
unsigned long int posible_primo;//El numero actual para verificar si es primo
unsigned long int pos;//auxiliar para recorrer el array
int es_primo;
for (posible_primo=3; posible_primo<maximo;posible_primo+=2){ // 3 5 7 9 11 ...
/*comprobamos si es primo buscando si en el array hay algun
numero primo que lo divida, pero solo hasta raiz de n*/
unsigned long int ult_pos = (sizeof(primos)/sizeof(primos[0]));//ultima posicion del array
es_primo = 1;//por defecto es primo
for(pos=0;(pos<ult_pos) && (primos[pos]<sqrt(posible_primo));pos++){
/*mientras el primo en la posicion pos sea menos que la raiz del
numero que queremos comprobar*/
if(posible_primo%primos[pos]==0){
//si es multiplo, entonces no es primo y salimos
es_primo = 0;
break;
}
}
if(es_primo==1){
primos[ult_pos+1]=posible_primo;
}
}
mostrar_primos(primos, (sizeof(primos)/sizeof(primos[0])));
cout<<"Fin"<<endl;
return 0;
}
My program returns:
Starting...
two
The end
I can't find the fault, it must be that I have made a mess with the loops...
Could someone tell me where is the error?
The inner loop loops one or two times before stopping at 1 so you never get to check the numbers you're interested in, the reason is that the expression that calculates the last position doesn't do what you think it does:
The size of
primos
(sizeof(primos)
) is not the number of elements in the array but the size of the pointer, which will be 4 or 8 bytes (depending on the architecture of your system), the size ofprimos[0]
will also be 4 or 8 bytes so it willult_pos
always return 1 or 2.You have the same problem trying to display the data 1 as you display one or two elements because the split returns 1 or 2:
Proposal.
bool
non-integer type for logical results.sqrt
is expensive, don't calculate it on each turn of the inner loop.Following these tips your code could look like:
You can see the code working in Try it online!.
1 Thing you would have noticed if you had debugged the code.