예제 #1
0
        public static List <Prime> CalculatePrimeFactorization(int number)
        {
            if (number == 0)
            {
                return(new List <Prime>());
            }
            if (number == 1)
            {
                return new List <Prime>()
                       {
                           new Prime(1, 1)
                       }
            }
            ;

            List <Prime> resultLst = new List <Prime>();

            // Divide number through first prime number till it's isn't possible
            // If number is finally a prime number, we can exit
            Prime currentPrime  = new Prime();
            int   currentNumber = number;
            int   currentP      = 2;
            bool  isAdded       = false;
            bool  addedFirst    = false;
            bool  noLoop        = true;

            while (!IsPrimeNumber(currentNumber))
            {
                noLoop = false;

                if (currentNumber % currentP == 0)
                {
                    currentNumber /= currentP;
                    currentPrime.Virility++;
                    isAdded    = false;
                    addedFirst = true;
                }
                else
                {
                    if (addedFirst)
                    {
                        isAdded             = true;
                        addedFirst          = false;
                        currentPrime.Number = currentP;
                        resultLst.Add(currentPrime);
                        currentPrime = new Prime();
                    }
                    currentP = calculateNextPrimeNumber(currentP);
                }
            }

            if (noLoop) // Primenumber
            {
                currentP = currentNumber;
                currentPrime.Virility = 1;
            }
            if (!isAdded)
            {
                currentPrime.Number = currentP;
                resultLst.Add(currentPrime);
            }

            if (resultLst.Count() == 0)
            {
                resultLst.Add(new Prime(number, 1));
            }
            else if (currentNumber > 0 && !noLoop)
            {
                bool found = false;
                for (int i = 0; i <= resultLst.Count - 1; i++)
                {
                    if (resultLst[i].Number == currentNumber)
                    {
                        resultLst[i].Virility++;
                        found = true;
                        break;
                    }
                }
                if (!found)
                {
                    resultLst.Add(new Prime(currentNumber, 1));
                }
            }
            return(resultLst);
        }