📌  相关文章
📜  级数之和(n / 1)+(n / 2)+(n / 3)+(n / 4)+……。+(n / n)

📅  最后修改于: 2021-05-06 08:38:10             🧑  作者: Mango

给定一个值n,找到级数之和(n / 1)+(n / 2)+(n / 3)+(n / 4)+……。+(n / n),其中n的值可以达到10 ^ 12。
注意:仅考虑整数除法。
例子:

Input : n = 5
Output : (5/1) + (5/2) + (5/3) + 
        (5/4) + (5/5) = 5 + 2 + 1 + 1 + 1 
                      = 10

Input : 7
Output : (7/1) + (7/2) + (7/3) + (7/4) +
         (7/5) + (7/6) + (7/7) 
         = 7 + 3 + 2 + 1 + 1 + 1 + 1 
         = 16

以下是查找给定序列之和的程序:

C++
// CPP program to find
// sum of given series
#include 
using namespace std;
 
// function to find sum of series
long long int sum(long long int n)
{
    long long int root = sqrt(n);
    long long int ans = 0;
 
    for (int i = 1; i <= root; i++)
        ans += n / i;
     
    ans = 2 * ans - (root * root);
    return ans;
}
 
// driver code
int main()
{
    long long int n = 35;
    cout << sum(n);
    return 0;
}


Java
// Java program to find
// sum of given series
import java.util.*;
 
class GFG {
     
    // function to find sum of series
    static long sum(long n)
    {
        long root = (long)Math.sqrt(n);
        long ans = 0;
      
        for (int i = 1; i <= root; i++)
            ans += n / i;
          
        ans = 2 * ans - (root * root);
         
        return ans;
    }
     
    /* Driver code */
    public static void main(String[] args)
    {
        long n = 35;
        System.out.println(sum(n));
    }
}
     
// This code is contributed by Arnav Kr. Mandal.


Python3
# Python 3 program to find
# sum of given series
 
import math
 
# function to find sum of series
def sum(n) :
    root = (int)(math.sqrt(n))
    ans = 0
  
    for i in range(1, root + 1) :
        ans = ans + n // i
      
    ans = 2 * ans - (root * root)
    return ans
 
# driver code
n = 35
print(sum(n))
 
# This code is contributed by Nikita Tiwari.


C#
// C# program to find
// sum of given series
using System;
 
class GFG {
     
    // Function to find sum of series
    static long sum(long n)
    {
        long root = (long)Math.Sqrt(n);
        long ans = 0;
     
        for (int i = 1; i <= root; i++)
            ans += n / i;
         
        ans = 2 * ans - (root * root);
         
        return ans;
    }
     
    // Driver code
    public static void Main()
    {
        long n = 35;
        Console.Write(sum(n));
    }
}
     
// This code is contributed vt_m.


PHP


Javascript


输出:

131

注意:如果仔细观察,我们可以看到,如果我们选择n个共同点,则级数会变成调和级数。