Java程序显示数字的因子

要理解此示例,您应了解以下Java编程主题


示例1:正整数的因子

public class Main {

  public static void main(String[] args) {

    // positive number
    int number = 60;

    System.out.print("Factors of " + number + " are: ");

    // loop runs from 1 to 60
    for (int i = 1; i <= number; ++i) {

      // if number is divided by i
      // i is the factor
      if (number % i == 0) {
        System.out.print(i + " ");
      }
    }
  }
}

输出

Factors of 60 are: 1 2 3 4 5 6 10 12 15 20 30 60

在上面的程序中,需要查找因数的数字存储在变量number(60)中。

for循环会一直迭代,直到i <= number变为false。在每次迭代中,都会检查number是否能被i整除(这是i成为number因数的条件),并且i的值会增加1。


示例2:负数的因子

class Main {

  public static void main(String[] args) {

    // negative number
    int number = -60;
    System.out.print("Factors of " + number + " are: ");

    // run loop from -60 to 60
    for(int i = number; i <= Math.abs(number); ++i) {

      // skips the iteration for i = 0
      if(i == 0) {
        continue;
      }
      else {
        if (number % i == 0) {
          System.out.print(i + " ");
        }
      }
    }
  }
}

输出

Factors of -60 are: -60 -30 -20 -15 -12 -10 -6 -5 -4 -3 -2 -1 1 2 3 4 5 6 10 12 15 20 30 60  

在上面的示例中,我们计算了一个负数的所有因子。这里,for循环的范围是从-6060

并且,当i的值为0时,会跳过该迭代。否则,将导致异常。

注意Math.abs()方法返回数字的绝对值。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战