Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum sequence?

How can I sum the following sequence:

⌊n/1⌋ + ⌊n/2⌋ + ⌊n/3⌋ + ... + ⌊n/n⌋

This is simply O(n) solution on C++:

#include <iostream>
int main()
{
   int n;
   std::cin>>n;
   unsigned long long res=0;
   for (int i=1;i<=n;i++)
   {
      res+= n/i;
   }
   std::cout<<res<<std::endl;
   return 0;
}

Do you know any better solution than this? I mean O(1) or O(log(n)). Thank you for your time :) and solutions

Edit: Thank you for all your answers. If someone wants the solution O(sqrt(n)): Python:

import math
def seq_sum(n):
 sqrtn = int(math.sqrt(n))
 return sum(n // k for k in range(1, sqrtn + 1)) * 2 - sqrtn ** 2
n = int(input())
print(seq_sum(n))

C++:

#include <iostream>
#include <cmath>
int main()
{
   int n;
   std::cin>>n;
   int sqrtn = (int)(std::sqrt(n));
   long long res2 = 0;
   for (int i=1;i<=sqrtn;i++)
   {
      res2 +=2*(n/i);
   }
   res2 -= sqrtn*sqrtn;
   std::cout<<res2<<std::endl;
   return 0;
}
like image 736
vasylysk Avatar asked Jan 04 '15 18:01

vasylysk


People also ask

What is the formula to calculate sequence?

sequence determined by a = 2 and d = 3. Solution: To find a specific term of an arithmetic sequence, we use the formula for finding the nth term. Step 1: The nth term of an arithmetic sequence is given by an = a + (n – 1)d. So, to find the nth term, substitute the given values a = 2 and d = 3 into the formula.

What is the sum of the terms of a sequence?

The sum of the terms of a sequence is called a series .


2 Answers

This is Dirichlet's divisor summatory function D(x). Using the following formula (source)

D(x)

where

u

gives the following O(sqrt(n)) psuedo-code (that happens to be valid Python):

def seq_sum(n):
  sqrtn = int(math.sqrt(n))
  return sum(n // k for k in range(1, sqrtn + 1)) * 2 - sqrtn ** 2

Notes:

  • The // operator in Python is integer, that is truncating, division.
  • math.sqrt() is used as an illustration. Strictly speaking, this should use an exact integer square root algorithm instead of floating-point maths.
like image 146
NPE Avatar answered Oct 13 '22 18:10

NPE


Taken from the Wikipedia article on the Divisor summatory function,

enter image description here

where enter image description here. That should provide an enter image description here time solution.

EDIT: the integer square root problem can also be solved in square root or even logarithmic time too - just in case that isn't obvious.

like image 42
Alec Avatar answered Oct 13 '22 17:10

Alec