找出一个正整数的所有因子(因数)
这里使用静态方法
public static TreeSet<Integer> FindFactors(int i){
if (i<=0){
System.out.println("i必须是大于0的自然数");
return null;
}
TreeSet<Integer> factors = new TreeSet<>();//使用TreeSet保证元素不重复且因子自动升序
if (i!=1) { //判断i不为1
int num = 2; //先设除数为2,可能为除1外最小因子
while (true) {
if (i % num == 0) { //模为0时就把该元素添加到集合中
factors.add(num);
}
num++; //除数不断自增
if (num > (i >> 1)) { //当除数大于i的一半时,打破循环,如果有什么效率更高的,可以评论写下
break;
}
}
factors.add(1);
factors.add(i); //因数还有1和i本身
}
else {
factors.add(1); //i为1时因数只有1
}
for (Integer nums:factors) { //遍历输出一下
System.out.println(nums);
}
return factors;
}