I have been offered a mobile application where you ask for the position of a prime number and it returns the prime number in that position. Specifically, I start by storing only the prime numbers in an ArrayList and then I have optimized everything that has occurred to me so as not to block the mobile but in the end it explodes, I don't know what further optimizations to make, can someone help me please? Thank you very much and greetings to all.
Here I show the code:
All of the following is inside a package and I import the corresponding libraries, which I do not put here because it gives me an error and does not let me publish.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
static ArrayList<Integer> nprimos = new ArrayList<Integer>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
Button btnCalcular=findViewById(R.id.btnCalcular);
btnCalcular.setOnClickListener(this);
int numero=2;
boolean primo=false;
nprimos.add(1);//Hago un add inicial en el ArrayList
for(int j=0;j<100000;j++){//Hago el bucle for hasta 100000 posiciones
primo=true;
for(int i=2; i<nprimos.size(); i++)//Hago el bucle for mientras sea menor del tamaño
//del ArrayList
{
if(numero%nprimos.get(i)==0) {//divide solo entre los números primos
primo = false;//Si no es primo
break;//termina el for y salta a numero++
}
}
if(primo)
{//Si el número es primo le añado al ArrayList
nprimos.add(numero);
}//incremento la variable número y sube arriba para hacer la division en el if
//mientras j siga siendo menor de 100000
numero++;
}
}
public void onClick(View v){
EditText ed1=findViewById(R.id.ed1);
int num = Integer.parseInt(ed1.getText().toString());
TextView t=findViewById(R.id.txtResultado);
//Al pinchar ya empezamos con un ArrayList lleno de números primos
if(num<nprimos.size()){
t.setText("El número primo es: "+nprimos.get(num));
}
else{
int contador=0;
int limite=num-nprimos.size();
int numero=nprimos.get(nprimos.size()-1);
boolean primo=false;
while(contador!=limite) {
primo=true;
for(int i=2; i<nprimos.size(); i++)
{
if(numero%nprimos.get(i)==0) {
primo=false;
break;
}
}
if(primo)
{
contador++;
nprimos.add(numero);
}
numero++;
}
t.setText("El número primo es: "+nprimos.get(num-1));
}
}
}
I don't see that the program agrees with the question.
They give you the position of a prime number and you must find the prime number and not the other way around.
Let's see For n = 123 what is the prime number found there?
Let's use the following formula: 2^(n–1)(2^n – 1) is the perfect number theorem whenever 2^n - 1 is a prime number.