CCF NOI1024. 因子个数

版权声明:代码属于原创,转载请联系作者并注明出处。 https://blog.csdn.net/weixin_43379056/article/details/84927387

1024. 因子个数

题目描述

对于任意给定的一个正整数,计算其因数个数。

输入样例:

6

输出样例:

4

说明:
1、2、3、6都是6的因数。因此,输出4。

输入

输入正整数N。

输出

输出N的因子个数。

样例输入

6

样例输出

4

数据范围限制

1<=N<2^31

C++代码

#include <iostream>
#include <cmath>
#include <cassert>

using namespace std;

int main()
{
    int N;

    cin >> N;

    assert(N >= 1);

    int numOfDivisors;

    if (1 == N)
    {
        numOfDivisors = 1;  // 1 has only one divisor
    }
    else
    {
        numOfDivisors = 2;  // 1 and itself are its divisor

        for(int i=2; i<=(int)sqrt((double)N); i++)
        {
            if (N%i == 0)
            {
                if (i*i == N)
                {
                    numOfDivisors++;  // i = N/i only divisor
                }
                else
                {
                    numOfDivisors +=2; // i and N/i are its divisors
                }
            }
        }
    }

    cout << numOfDivisors << endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43379056/article/details/84927387