• + 0 comments

    In C#

    I tried dividing as I go throug the loop. If the division results didn't have any decimals, then I added both numbers to the set. This way I only go through half the numbers.

    public class Calculator : AdvancedArithmetic
    {
        HashSet<int> divisors = new HashSet<int>();
        public int divisorSum(int n)
        {
            int half = (int)Math.Ceiling(n / 2.0);
            for(int i = 1; i <= half; i++){
                double div = n / (double)i;
                if(div % 1 == 0)
                {
                    divisors.Add(i);
                    divisors.Add((int)div);
                }          
            }
            return divisors.Sum();
        }
    }