给定n个数,求这n个数因子个数和。
例如n=3
3 4 10
3的因子有1 3
4的因子有1 2 4
10的因子有1 2 5 10
所以个数是2+3+4=9
折半查找要比挨个查询快得多,而根据平方根要比折半查找更快。
public class Pan {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int x=1;x<=20;x++)
System.out.println(solve(x));
}
public static int solve(int x)
{
int count=0,i;
for(i=1;i<Math.sqrt(x);i++)
{
if(x%i==0)
count+=2;
}
if(i==Math.sqrt(x)&&x==i*i)
count++;
return count;
}
}
本文介绍了一种快速计算给定整数因子个数的方法,通过遍历至平方根并考虑完全平方数来减少计算量,提高了效率。
598

被折叠的 条评论
为什么被折叠?



