250. 水仙花數(shù)1
題目描述
水仙花數(shù)是指一個N位正整數(shù)(N>=3),它的每個位上的數(shù)字的N次冪之和等于它本身。
例如:
153 = 1^3 + 5^3+ 3^3.
1634 = 1^4 + 6^4 + 3^4 + 4^4.
本題要求編寫程序,計算所有N位水仙花數(shù)。
解答要求時間限制:2000ms, 內(nèi)存限制:100MB
輸入
輸入的測試數(shù)據(jù)只有一行, 一個數(shù)字 N(輸入數(shù)據(jù)保證 N >= 3 并且 N < 8)表示要求輸出的水仙花數(shù)的位數(shù).
輸出
每組測試數(shù)據(jù)輸出包括很多行。首先按照從小到大的順序輸出滿足要求的數(shù), 每個數(shù)一行;最后輸出一個整數(shù), 代表滿足要求的數(shù)的個數(shù).
樣例
輸入樣例 1 復(fù)制
3
輸出樣例 1
153 370 371 407 4
思路:暴力可做
代碼:
// we have defined the necessary header files here for this problem. // If additional header files are needed in your program, please import here. #include<iostream> using namespace std; int mathPow(int a, int b) { int res = 1; for (int i = 0; i < b; i++) { res *= a; } return res; } int judge(int N,int num) { int b,k; int ori = num; int sum = 0; while(num>0) { b = num%10; num /= 10; sum+=mathPow(b,N); } if(sum == ori) { return 1; } else{ return 0; } } int main() { // please define the C++ input here. For example: int a,b; cin>>a>>b;; // please finish the function body here. // please define the C++ output here. For example:cout<<____<<endl; int N; cin>>N; int low = mathPow(10,N-1); int high = mathPow(10,N); int cnt = 0; for(int i =low;i<high;i++) { if(judge(N,i) == 1) { cnt++; cout<<i<<endl; } } cout<<cnt<<endl; return 0; }
以大多數(shù)人努力程度之低,根本輪不到去拼天賦~

浙公網(wǎng)安備 33010602011771號