在Java中如何查找给定数字的随机因子

时间:2015-11-16 19:25:49

标签: java

我有一个给定的号码。如何找到该数字的因子(例如,数字15的5和3)?这是我试过的代码:

int factor1 = 2;

while ((a % factor1 != 0) && (a >= factor1)) {
    d++;
}

if (factor1 == a){
    d = 1;
}

但这只给出了最小的因素(即a = 3)。我想得到一组随机因素。

5 个答案:

答案 0 :(得分:2)

使用模运算符(%)循环遍历从1到N的每个数字。如果是n%currentNumber==0,则它们是一个因素。下面,我使用for循环执行此操作,输出找到的每个因子。

    int number=15;
    for(int i = 1; i <= number; i++){
        if(number%i==0){
            System.out.println("Found factor: " + i);
        }
    }

正如Theo在对此帖子的评论中所说,您也可以使用number/2,并随意包含1和number

    int number=2229348;
    System.out.println("Found factor: " + 1);
    for(int i = 2; i <= number/2; i++){
        if(number%i==0){
            System.out.println("Found factor: " + i);
        }
    }
    System.out.println("Found factor: " + number);

答案 1 :(得分:1)

您可以遍历从2a/2的数字,并检查给定的数字是否除以a,这是使用%运算符完成的:

int a = 15;
System.out.print("Divisors of " + a + ": ");
for(int i = 2; i <= a/2; ++i) {
    if(a % i == 0) {
        System.out.print(i + " ");
    }
}
System.out.println();

此代码打印a的所有除数。并非你最想忽略1,因为它除了所有整数。此外,您不需要在a之前检查数字,因为大于a / 2的数字实际上除了a之外实际上可以除a之外。

答案 2 :(得分:0)

默认值为a = 15且倍数= 2的while循环已经处于无限循环中。你需要纠正这个问题,并在%倍数时检查后续的倍数增量! = 0

公共阶层因素{

public static void main(String[] args){
    /**
    int multiple1=2,d=0,a=15; //multiple to be rephrased as factor

    while((a%multiple1 != 0)&&(a>=multiple1)){
        multiple1++; //this will increment the factor and check till the number itself
        //System.out.println(multiple1+" is not a factor of a");

    }
    if(multiple1==a){
        d=1;
    }
     *commented the original code
     */ 


    int factor=1,d=0,a=20; //multiple rephrased as factor

    while(a/2>=factor){  //re-arranged your while condition
        factor++;
        if((a%factor==0))
                d++;      //increment factor count whenever a factor is found
    }

    System.out.println("Total number of factors of a : "+(d+2)); // 1 and 'a' are by default factors of number 'a'
}

}

答案 3 :(得分:0)

要查找包含1和数字本身的所有因素,您可以执行以下操作:

//Iterate from 2 until n/2 (inclusive) and divide n by each number.
// Return numbers that are factors (i.e. remainder = 0) and are prime
int[] findPrimeFactors(int number) {
  return IntStream.range(2, 1 + number/ 2).filter(factor -> number % factor == 0 && isPrime(factor)).toArray();
}

要找到素数因素,您可以执行以下操作:

//Iterate from 2 until n/2 (inclusive) and divide n by each number. Return false if at least one divisor is found
boolean isPrime(int n) {
 if (n <= 1) throw new RuntimeException("Invalid input");
 return !IntStream.range(2, 1+n/2).filter(x -> ((n % x == 0) && (x != n))).findFirst().isPresent();
}

素性检查的辅助方法:

//Find all factors of a number
public Set<Integer> findFactors(int number) {
    Set<Integer> factors = new TreeSet<>();
    int i = 1;
    factors.add(i);
    while (i++ < 1 + number / 2) {
      if ((number % i) == 0) {
        factors.add(i);
      }
    }
    factors.add(number);
    return factors;
}

如果您不使用Java 8和/或不使用Lambda表达式,则可以使用以下简单的迭代循环:

class Player(object):
    def __init__(self, name, health):
        self._name = name
        self._health = health

    def get_health(self):
        """Return the players health."""
        ## LINE ##

答案 4 :(得分:-1)

public class Abc{
public static void main(String...args){
    if(args.length<2){
        System.out.println("Usage : java Abc 22 3");
        System.exit(1);
    }
    int no1=Integer.parseInt(args[0]);
    int no=Integer.parseInt(args[1]),temp=0,i;
    for(i=no;i<=no1;i+=no){
        temp++;
    }

    System.out.println("Multiple of "+no+" to get "+no1+" is :--> "+temp);
    //System.out.println(i+"--"+no1+"---"+no);
    System.out.println("Reminder is "+(no1-i+no));
}

}