Summation program

You are given a number N. You are required to determine the value of the following function:

long long int solve(N)

{

ans=0;

for(i=1;I<=N;i++)

  ans+=(N/i)

return and;

}

All divisions are integer divisions(i.e. N/i is actually floor(N/i)).

Example:

Input:  n=5
Output: 10

Approach

C++

#include <bits/stdc++.h>
using namespace std;

int main()
{

    long long n = 5;
    long long sum = 0;
    long long i = nj = 2p = 1;
    while (true)
    {
        long long k = n / j;
        if (i == k)
            break;
        else
        {
            sum += (i - k) * p;
            j++;
            i = k;
            p++;
        }
    }
    while (i > 0)
    {
        sum += n / i;
        i--;
    }
    cout << sum << "\n";
    return 0;
}


No comments:

Post a Comment