Find then sum all the divisors from 1 to N.
The main problem is, that this code runs really poor with high numbers.
The following code was taken from: https://www.geeksforgeeks.org/sum-divisors-1-n
static int divisorSum(int n)
{
int sum = 0;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j * j <= i; ++j)
{
if (i % j == 0)
{
if (i / j == j)
sum += j;
else
sum += j + i / j;
}
}
}
return sum;
}
Based on @Joel solution, I just improved it:
static long divisorSum(int n)
{
long sum = 0;
for (long i = 1; i <= n/2; ++i)
sum += i * (n / i);
sum += (n/2+1+n)*(n-n/2)/2; // It's a sum of an arithmetic progression
return sum;
}
For i
> n/2
the expression i * (n / i)
is simply i
(because n/i
= 1), so we can get the sum of all the numbers between n/2 + 1
to n
by computing a sum of an arithmetic progression. It will run faster, although it is O(n)
too.
There is no need to use a collection of sorts, since you sum everything up and don't need to think about duplicates. I don't think there is a way to get a solution for this which is a perfect O(n)
, but this is the closest I can think of:
int sum = 0;
for (int i = 1; i <= n; i++)
{
double sqrt = Math.Sqrt (i);
for (int j = 1; j <= sqrt; j++)
{
if (i % j == 0)
{
sum += j;
if (j != sqrt)
sum += i / j;
}
}
}
Divisors are pairs, so there isn't a need to go all the way to i
every time (eg 1 * 10
, 10 * 1
are the same). You can go till the square-root of i
(the 'mid-point'), and save time, hence it's not O(n^2)
, but not perfectly O(n)
.
You could do something like this O(n)
:
static long divisorSum(int n)
{
long sum = 0;
for (long i = 1; i <= n; ++i)
sum += i * (n / i);
return sum;
}
static void Main(string[] args)
{
int val = 129999;
Console.WriteLine(divisorSum(val));
Console.ReadLine();
}
Tests:
12999 => 8ms
129999 => 25ms
2147483647 => 18770ms (Max Int32 value)
int val = 129999;
int maxInt = int.MaxValue;
//val (129999)
var watch = System.Diagnostics.Stopwatch.StartNew();
Console.WriteLine(divisorSum(val));
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine(elapsedMs); //25ms
//MaxInt (2147483647)
watch = System.Diagnostics.Stopwatch.StartNew();
Console.WriteLine(divisorSum(maxInt));
watch.Stop();
elapsedMs = watch.ElapsedMilliseconds; //18770ms
Console.WriteLine(elapsedMs);
Console.ReadLine();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.