Solution of 11526 - H(n)

Problem Description
source: https://uva.onlinejudge.org/external/115/11526.html

What is the value this simple C++ function will return? 

long long H(int n){ 
    long long res = 0;
    for( int i = 1; i <= n; i=i+1 ){
        res = (res + n/i);
    } 
    return res; 
} 


Input

The first line of input is an integer T (T ≤ 1000) that indicates the number of test cases. Each of the next T line will contain a single signed 32 bit integer n. 

Output

 For each test case, output will be a single line containing H(n). 

Sample Input

2 5 10 

Sample Output

10 27

Solution
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include<stdio.h>
#include<stdlib.h>

using namespace std;

int main()
{
    long long int n,sum,i,j,k,rootn,loop1,loop2,t,noOfj;
    //freopen("input.txt","r",stdin);
    while(scanf("%lld",&t)==1)
    {
        for(k=1;k<=t;k++)
        {
            scanf("%lld",&n);
            loop1=0;
            loop2=0;
            sum=0;
            rootn=sqrt(n);
            for(j=1;j<=rootn;j++)
            {
                noOfj=(n/j)-(n/(j+1));
                loop1+=noOfj;
                sum+=noOfj*j;
            }
            loop2=n-loop1;
            for(i=1;i<=loop2;i++)
            {
                sum+=n/i;
            }
            printf("%lld\n",sum);
        }
    }
    return 0;
}
image

No comments:

Post a Comment

Write your comment - Share Knowledge and Experience