【问题标题】:Printing Common Divisors of Inputted Positive Integers打印输入正整数的公约数
【发布时间】:2019-10-06 01:41:41
【问题描述】:

我需要打印输入的两个正整数之间的公约数。它们需要按升序打印。如果它们是相对质数,则需要打印“1”。我这里的代码远非正确。我真的很困惑如何正确使用循环,同时保持升序。

示例输入:

整数 a:8 整数 b:12

样本输出:

8 和 12 的公因数:

1

2

4

8 和 12 不是互质数。

备用输入:

整数 a:8 整数 b:9

8 和 9 的公因数:

1

8 和 9 互质。

import java.util.Scanner;

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

 int num1 = scnr.nextInt();
  int num2 = scnr.nextInt();
  System.out.println("Common divisors of " + num1 + " and " + num2 + ":");

  int div1 = 0;
  int div2 = 0;
  int same = 0;
  for (int i=1;i<=num1;i++) {
    while (div1 <= num1) {
      div1 = num1/i;
    }
    while (div2 <= num2) {
      div2 = num2/i;
    }
    if (div1 == div2) {
      div1 += same;
      System.out.println(same);
      System.out.println(num1 + " and " + num2 + " are not relatively prime.");
    }
    if (div1 != div2) {
      System.out.println(1);
      System.out.println(num1 + " and " + num2 + " are relatively prime.");
    }
    }
}
}

【问题讨论】:

标签: java loops


【解决方案1】:

您可以尝试以下简单的方法:

import java.util.Scanner;

 public class RelativelyPrime {
      public static void main(String[] args) {
          Scanner scnr = new Scanner(System.in);  
          int num1 = scnr.nextInt();
          int num2 = scnr.nextInt();
          System.out.println("Common divisors of " + num1 + " and " + num2 + ":");
          for(int i = 1; i<= Math.min(num1,num2); i++){
            if(num1%i==0 && num2%i==0) {
               System.out.println(i);
            }
          } 
       }
}

【讨论】:

    【解决方案2】:
    Scanner input = new Scanner (System.in);
    num1 = input.nextInt();
    num2 = input.nextInt();
    List<Integer> list = new ArrayList<>();
    
    for(int i=0; i<=Math.min(num1,num2);i++){
     if(num1%i==0 && num2%i==0){
     list.add(i);
    }
      }
    
    System.out.println("Divisors:");
    
    for(int a : list){
     System.out.println(a);  }
    
    if(list.size()<2){
     System.out.print("Not Relatively Prime");  }
    
    else { System.out.print("Relatively Prime");}
    

    【讨论】:

      猜你喜欢
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2022-10-22
      相关资源
      最近更新 更多