Divisors of a number which variable to print

Asked

Viewed 120 times

-1

I came across a problem with the splitters of a number and that also goes to other problems

I made this code to print me number dividers from largest to smallest, but it is just printing one of the dividers. How can I solve this?

import java.util.Scanner;

public class ex1dd {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);

        int x=0;
        int y=0;

        System.out.println("Dá-me 2 números");
        x= sc.nextInt();
        y=sc.nextInt();



        for (int i =x;i<=y;i++) {
            if (i %y == 0){
                System.out.println(i);
            }

        }
    }
}
  • If you want the dividers of y which are greater than or equal to x then use: if (y % i == 0){

  • the problem for not exiting the expected result is in this line: "if (i % y == 0)" as it is a programming logic problem, try to solve, I guarantee you can! tip: use "System.out.println(i);" before if

  • thanks @Nunes I’m just starting out in college and my teacher is really bad and I have to do at home, since you mentioned in programming logic some website tip or something to improve in that aspect

1 answer

0


From what you can understand, you want to print the divisors of a number x between x and another number y. The error happens because of the line:

if (i %y == 0)

Under this condition, the y only, which, in the context of the programme, will be y. To correct, replace the line with:

if (i % x == 0)

The whole code goes like this:

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);

        int x=0;
        int y=0;

        System.out.println("Dá-me 2 números");
        x= sc.nextInt();
        y=sc.nextInt();



        for (int i =x;i<=y;i++) {
            if (i % x == 0){
                System.out.println(i);
            }

        }
    }
  }

A tip to optimize the code: knowing that a number is always splitter of itself, you can print, before the loop for, the number x eliminating a comparison.

See working on repl.it

  • Hello John even using the edition you proposed to me he is only printing the values I put there. For example Give me 2 numbers 50 10 Process finished with Exit code 0

  • This is the exercise I have to solve-Write the divisors of a number (from the largest to the smallest).

  • Taking into account that a number has infinite divisors, it is impossible to print all divisors from the largest to the smallest because you do not know which is the largest (since theoretically it is infinite). What you can do is use the second variable as an upper bound, and invert the is, starting from x and going up to y. I edited the code in repl.it to do this, just look there.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.