Waiter

  • + 0 comments

    C#

    public static List<int> waiter(List<int> number, int q)
        {
            List<int> result = new List<int>();
            foreach (int p in GetFirstKPrimes(q)) {
                var b = new List<int>();
                var a = new List<int>();
                for (int i = number.Count()-1; i >= 0; i--) {
                    if (number[i] % p == 0) b.Add(number[i]);
                    else a.Add(number[i]);
                }
                b.Reverse();
                result.AddRange(b);
                
                number = a;
            }
            
            number.Reverse();
            result.AddRange(number);
            return result;
        }
        
        private static List<int> GetFirstKPrimes(int k) {
            bool[] nums = new bool[10_000];
            Array.Fill(nums, true);
            nums[0] = false;
            nums[1] = false;
            for (int i = 2; i < nums.Length; i++) {
                if (nums[i]) {
                    for (int j = 2*i; j < nums.Length; j += i)
                        nums[j] = false;
                }
            }
            
            List<int> primes = new List<int>();
            for (int i = 2; i < nums.Length; i++)
                if (nums[i]) primes.Add(i);
                
            return primes.Take(k).ToList();
        }