Print the numbers of form 2^i.5^j in increasing order -- Google

Problem
Print the numbers of form 2^i.5^j in increasing order. For eg: 
1, 2, 4, 5, 8, 10, 16, 20

Solution

using System;
using System.Collections.Generic;

namespace JamesChen
{
    class PrintNumIncreasingly
    {
        static void PrintIncreasingNums(int n)
        {
            if (n < 0) return;
            List<int> a = new List<int>();
            a.Add(1);

            int count2 = 0;  
            int count5 = 0;
            
            while (a.Count < n)
            {
                if (a[count2] * 2 < a[count5] * 5)
                {
                    a.Add(a[count2] * 2);
                    count2++;
                }
                else if (a[count2] * 2 > a[count5] * 5)
                {
                    a.Add(a[count5] * 5);
                    count5++;
                }
                else
                {
                    a.Add(a[count5] * 5);
                    count2++;
                    count5++;
                }
            }

            foreach (var i in a)
            {
                Console.Write("{0, 6}", i);
            }
            Console.WriteLine();
        }

        static void Main(string[] args)
        {
            PrintIncreasingNums(20);
        }
    }
}

Output
     1     2     4     5     8    10    16    20    25    32    40    50    64    80   100   125   128   160   200   250
Press any key to continue . . .
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章