Home > OS >  how to get loop to solve common divisor method
how to get loop to solve common divisor method

Time:12-06

how do I get this loop to print all the divisors with two user inputted numbers including 1 but just print 1 and relatively prime when the two numbers have no common divisors.

 System.out.println("Common divisors of "   a   " and "   b   ":");
        for (int i = 1; i <= b; i  )
            if (a % i == 0 && b % i == 0) {
               if (a % i == 0 && b % i == 0) {
                    System.out.println(i);
                if (i == 1)
                    System.out.println("Relatively Prime");


            }
    }
    
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter two positive integers:");
        int input1 = scan.nextInt();
        int input2 = scan.nextInt();
        printCommonDivisors(input1, input2);
    }
}

Right now it says relatively prime after 1 even if the numbers have common divisors.

I am just trying to get it to say relatively prime when the two numbers only common divisor is 1 but also not print relatively prime after 1 when the numbers do have more common divisors. this the output right now. Please enter two positive integers: 10 20 Common divisors of 10 and 20: 1 Relatively Prime 2 5 10

CodePudding user response:

You need a boolean value to store whether you have found a greater-than-one divisor inside the loop. Instead of

if (i == 1)
  System.out.println("Relatively Prime");

Check the boolean value after the loop and print "Relatively Prime" if a divisor was not found.

You have the line if (a % i == 0 && b % i == 0) { twice, you only need to have one of it, make sure to remove the closing brace for it as well.

CodePudding user response:

If you want to print "relatively prime" only if there were no other divisors, you should check for other divisors first (for instance by starting with the large numbers and working your way down, rather than starting with small numbers and work your way up) and if you find one, somehow record this fact so you later know not print "relatively prime".

In code:

boolean divisorFound = false;
for (int i = b; i > 1; i--) {
  if (a % i == 0 && b % i == 0) {
    System.out.println(i);
    divisorFound = true;
  }
}
System.out.println(1);
if (!divisorFound) {
  System.out.println("relatively prime");
}

Of course, there are more efficient algorithms. For instance, one could use euklid's algorithm to efficiently determind the greatest common divisor, then find its prime factors, and use that to efficiently iterate all divisors.

  • Related