For 3 and 5 there is circular dependence every 15 (3*5=15) that is why we can just do something like this:
static void Main()
{
int[] deltas= { 3,2,1,3,1,2,3 };
int number = 30;
List<int> result = new List<int>();
int j = 1;
for(int i = deltas[0]; i<=number; i+=deltas[j++%deltas.Length])
{
result.Add(i);
}
foreach(int i in result)
Console.Write(i+", ");
}
Update:
To find circular point we need to calculate Least Common Multiple. Now to find all deltas to that point we just need resolves original problem in less optimal way and subtracts elements from each other.
More generic version:
static void Main()
{
foreach(int i in multi(30, new []{2,3,4,5,7} ))
Console.Write(i+", ");
}
static List<int> multi(int max, int[] divs)
{
int[] deltas = calcDeltas(divs);
List<int> result = new List<int>();
int j = 1;
for(int i = deltas[0]; i<=max; i+=deltas[j++%deltas.Length])
{
result.Add(i);
}
return result;
}
static int[] calcDeltas(int[] divs)
{
long max = 1;
foreach(int div in divs)
max = lcm(max,div);
List<long> ret = new List<long>();
foreach(int div in divs)
{
for(int i=div; i<=max; i+=div)
{
int idx = ret.BinarySearch(i);
if (idx < 0)
{
ret.Insert(~idx, i);
}
}
}
for(int i=ret.Count-1; i>0; i--)
ret[i]-=ret[i-1];
return ret.ConvertAll(x => (int)x).ToArray();
}
static long gcf(long a, long b)
{
while (b != 0)
{
long temp = b;
b = a % b;
a = temp;
}
return a;
}
static long lcm(long a, long b)
{
return (a / gcf(a, b)) * b;
}
Update 2:
I do some tests for provided solutions (without Eric's solution). I modify some functions to give exact same result (more in description). Tested on i7-3770K@3.5GH.
Username - description
Time 1 - Average time, loops = 100, number = 10000000
Time 2 - Total time, loops = 100000, number = 10000
Time 3 - Total time, loops = 1000000, number = 100
CPU Usage - in percentage
Mrinal Kamboj - with OrderBy as suggested to preserve correct order
434ms, 85447ms, 348600ms, 70%
Mrinal Kamboj - with OrderBy as suggested to preserve correct order, without ToList() instead to materialize query done ForAll(x=>{})
136ms, 51266ms, 273409ms, 80%
Mrinal Kamboj - without AsParallel
154ms, 14559ms, 1985ms, 13%
Mhd - second solution
69ms, 5791ms, 879ms, 13%
ThomW - added condition to prevent duplicates
34ms, 2398ms, 521ms, 13%
Logman - with precalculated deltas for 3,5 as original answer
43ms, 3498ms, 654ms, 13%
Logman - generic solution
47ms, 3529ms, 1270ms, 13%
Logman + HABO - with precalculated deltas for 3,5
37ms, 2655ms, 501ms, 13%
Logman + HABO - generic solution
37ms, 2701ms, 1149ms, 13%
HABO - Unrolled solution (see the comment)
32ms, 2072ms, 464ms, 13%
Test code