How to print all the divisible numbers of a number entered by keyboard? Java For

0

Hello, good, I'm doing a program where I must perform the division of two numbers and if it evaluates if the first number is divisible by the divisor, if so, print all the divisible divisible numbers. So far I did odd and even numbers, but it only works if I enter 2 or 3, what happens if I want to enter a 7 or an 8, I do not get their dividers, how could I do that? , that is, I want to enter any number and give me its first 10 divisible numbers. I hope it was clear. Now I leave you what I did:

public class Divisibles {

public static void main(String[] args) {

    Scanner teclado = new Scanner (System.in);
     int numero1 =0;
     int numero2 = 0;
     int par = 0;
     int impar = 0;
     int suma1=0;
     int suma2=0;
     System.out.println("Ingrese numero : ");
     numero1 = teclado.nextInt();
    System.out.println("Ingrese otro :");
    numero2 = teclado.nextInt();

     for(int i = 0 ; i<10 ; i++) {

         if(numero1%numero2==0) {

            if(numero2%2==0) {

                par+=2; //tuve que realizar esto por que sino no 
                        //salian numeros como el 16 o 18.
                suma1=par;

                System.out.println(suma1);

            }

            else if(numero2%3==0) { 


                impar+=3; //lo mismo aca le sume 3 por que no 
                          //salian numeros como el 9
                suma2=impar;

                System.out.println(suma2);
            }




         }




     }


}

}

Well I know that this program will work only for numbers divisible by 2 or 3, so if you have any idea of what could change, thank you:)

    
asked by computer96 02.12.2018 в 02:17
source

1 answer

1

This code gets you up to ten factors of a given number if it had them.

What it does is find the resto ( module ) of the division between the given number and all the numbers from 1 . If the module is equal to zero (nothing is left in the division), it means that the number is divisible by i .

The loop has a if inner to stop it when totalFactors reaches ten, to fulfill your requirement that it does not obtain more than 10 factors.

    int totalFactors=0;
    int theNumber=96;
    for(int i = 1; i <= theNumber; ++i) {
        /*Verificamos si no sobra nada en la división*/
        if (theNumber % i == 0) {
            totalFactors++;
            System.out.printf("%02d. %d\n" , totalFactors,i);
            /*Detenemos el bucle cuando haya 10 factores*/
            if (totalFactors==10){
                break;
            }
        }
    }

Exit:

The first ten factors of 96 , used as a test number would be:

01. 1
02. 2
03. 3
04. 4
05. 6
06. 8
07. 12
08. 16
09. 24
10. 32

Test code

VER DEMO EN REXTESTER     
answered by 02.12.2018 в 03:34