C#程序設計練習題五: 水仙花數

題目描述

春天是鮮花的季節,水仙花就是其中最迷人的代表,數學上有個水仙花數,他是這樣定義的: “水仙花數”是指一個三位數,它的各位數字的立方和等於其本身,比如:153=1^3+5^3+3^3。 現在要求輸出所有在m和n範圍內的水仙花數。

輸入

輸入數據有多組,每組佔一行,包括兩個整數m和n(100<=m<=n<=999)。

輸出

對於每個測試實例,要求輸出所有在給定範圍內的水仙花數,就是說,輸出的水仙花數必須大於等於 m,並且小於等於n,如果有多個,則要求從小到大排列在一行內輸出,之間用一個空格隔開; 如果給定的範圍內不存在水仙花數,則輸出no; 每個測試實例的輸出佔一行。

樣例輸入

copy

100 120 
300 380

樣例輸出

no
370 371

提示

 

杭電2010

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int p=1;
            while (p>0)
            {
                string s = Console.ReadLine();
                if (s == null || "".Equals(s))
                {
                    break;
                }
                string[] s1 = s.Split();
                int m = Convert.ToInt32(s1[0]);
                int n = Convert.ToInt32(s1[1]);
                wahh(m, n);
                Console.WriteLine();

            }
            Console.ReadKey();

        }

    
        static void wahh(int m, int n)
        {
            int[] akl = new int[1000];
            int flag = 0;
            int flag2 = 1;
            for (int i = m; i <= n; i++)
            {
                int sum = 0;
                int k = i;
                while (k != 0)
                {
                    int p = k % 10;
                    sum += p * p * p;
                    k = k / 10;
                    //Console.WriteLine(sum);
                }
                if (sum == i)
                {
                    flag = 1;
                    if (flag2 == 1)
                        Console.Write(sum);
                    else
                    {
                        Console.Write(" ");
                        Console.Write(sum);
                    }
                    flag2 = 0;
                }
            }
            if (flag == 0)
            {
                Console.Write("no");
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章