For that I need a function that gets every digit. In the following link, you can see a pretty good answer.
link
public static int obtener_digito(int numero, int posicion)
{
return (numero/(int)Math.pow(10,posicion))%10;
}
Using this function, you can check one by one, from the outside to the inside to see if the digits are the same.
public static Boolean es_capicua(int numero)
{
Boolean es_capicua_actual = true;
int longitud=(int) Math.log10(numero);
for (int i = 0; i <= longitud/2; i++)
{
int izquierda = obtener_digito(numero,i);
int derecha = obtener_digito(numero,longitud-i);
if( izquierda!=derecha )
{
es_capicua_actual = false;
break;
}
}
return es_capicua_actual;
}
A function is also needed to know if a number is prime. Luckily I found her, chewing a little about the site.
link
The only problem is that it is in C, but I convert it to Java.
public static Boolean es_primo(int numero)
{
Boolean es_primo_actual = true;
if(numero<2)
{
es_primo_actual = false;
}
else
{
for(int x=2; x*x<=numero; x++)
{
if( numero%x==0 ){es_primo_actual = false;break;}
}
}
return es_primo_actual;
}
Solving the main problem:
On the internet I found how to ask for data by keyboard. A scanner is declared, then numbers are required from the user, and finally the scanner is closed.
link
System.out.print ("Ingrese un numero del 2 al 15:\n");
Scanner teclado = new Scanner(System.in);
int n = teclado.nextInt();
teclado.close();
Also, how to show something on the screen.
link
System.out.print(i);
Then, you can check with a if
if the number is between 2
and 15
, this way. Finally, check that the numbers that are going to show are capicúas, cousins, and have a certain number of figures. For that use Math.pow
, to generate a number that is power of 10
, that is, we use the decimal number system.
if(n>=2 & n<=15)
{
int potencia_10_actual=(int) Math.pow(10,n-1);
int potencia_10_siguiente=10*potencia_10_actual;
for(int i=potencia_10_actual;i<potencia_10_siguiente;i++)
{
if( es_primo(i) && es_capicua(i) )
{
System.out.print (i+" ");
}
}
}