找到除数的数量

时间:2015-01-25 12:33:02

标签: c++

int checkdiv(int num)
{
    int SqrtOfnumber,i;
    SqrtOfnumber=sqrt(num);
    int counter=1;
    for(i=2;i<SqrtOfnumber;i++)
    {
        if(num%i==0)
        counter++;
    }
    counter=counter *2;
    if(i*i == num)
        counter++;
    return counter;
}

**如果2个数字具有相同的除数,则输出应为具有最小值的除数

输入示例

2           \\ test cases
1 10
1000 2000

预期产出

Between 1 and 10, 6 has a maximum of 4 divisors.
Between 1000 and 2000, 1680 has a maximum of 40 divisors.

上面的代码输出

Between 1 and 10, 10 has a maximum of 4 divisors.
Between 1000 and 2000, 1680 has a maximum of 38 divisors.

该函数返回错误的除数,而其余的代码可以正常工作,我该如何解决?

输入是一个数字,我想检查它有多少除数和除数的输出

1 个答案:

答案 0 :(得分:0)

问题的解决方法是使用 double 作为SquarOfnumber

int checkdiv(int x)
{
    double SqrtOfnumber;
    SqrtOfnumber=sqrt(x);
    int counter=1,i;
    for(i=2;i<SqrtOfnumber;i++)
    {
        if(x%i==0)
            counter++;
    }
    counter=counter*2;
    if(i*i == x)
    counter++;
    return counter;
}