/* (程序頭部註釋開始)
* 程序的版權和版本聲明部分
* Copyright (c) 2011, 煙臺大學計算機學院學生
* All rights reserved.
* 文件名稱: class nn
* 作 者: 劉程程
* 完成日期:
* 版 本 號: 1.0
* 對任務及求解方法的描述部分
* 輸入描述: 數字
* 問題描述: 判斷數字
* 程序輸出: 是否爲指定數字類型
* 程序頭部的註釋結束
*/
#include <iostream>
#include <Cmath>
using namespace std;
class NaturalNumber
{
private:
int n;
public:
void setValue (int x);//置數據成員n的值,要求判斷是否是正整數
int getValue();//返回私有成員n的值
bool isPrime();//判斷數據成員n是否爲素數,是返回true,否則返回false
void printFactor();//輸出數據成員n的所有因子,包括1和n自身
bool isPerfect(); //輸出數據成員n是否爲完全數,若一個正整數n的所有小於n的因子之和等於n, 則稱n爲完全數, 如6=1+2+3是完全數。
bool isReverse(int x);//判斷形式參數x是否爲數據成員n的逆向數(例321是123的逆向數)
bool isDaffodil(int x); //判斷形式參數x是否是水仙花數。水仙花數的各位數字立方和等於該數,如153=1*1*1+5*5*5+3*3*3
void printDaffodils(); //顯示所有大於1,且小於數據成員n的水仙花數;
};
//定義類中的各個成員函數
void NaturalNumber::setValue (int x)
{
n = x;
while( 1 )
{
if( x < 0)
exit( 0 );
else
break;
}
}
int NaturalNumber::getValue()
{
return n;
}
bool NaturalNumber::isPrime()
{
bool prime = true;
for(int i = 2;i <= sqrt(double( n )); i++)
{
if( n % i == 0 )
{
prime = false;
break;
}
}
return prime;
}
void NaturalNumber::printFactor() //輸出數據成員n的所有因子,包括和n自身
{
for( int i = 1; i<=n; i++)
if(n % i == 0)
cout << i << ' ';
cout<<endl;
}
bool NaturalNumber::isPerfect() //判斷數據成員n是否爲完全數。若一個正整數n的所有小於n的因子之和等於n, 則稱n爲完全數, 如=1+2+3是完全數。
{
bool perfect = false;
int s = 1;
for (int i = 2; i<n; i++)
if(n%i == 0)
s = s + i;
if (n == s)
perfect = true;
return perfect;
}
bool NaturalNumber::isReverse(int x)//判斷形式參數x是否爲數據成員n的逆向數(例是的逆向數)。
{
bool reverse = false;
int s = 0;
while ( x > 0)
{
s = s*10+x%10;
x = x/10;
}
if (n==s)
reverse = true;
return reverse;
}
bool NaturalNumber::isDaffodil(int x) //判斷形式參數x是否是水仙花數。水仙花數的各位數字立方和等於該數,如=1*1*1+5*5*5+3*3*3
{
bool daffodil=false;
int s=0,p=x;
int m;
while(p>0)
{
m=p%10;
s=s+m*m*m;
p=p/10;
}
if(x==s)
daffodil=true;
return daffodil;
}
void NaturalNumber::printDaffodils() //顯示所有大於,且小於數據成員n的水仙花數;
{
for(int i=2;i<n;++i)
if(isDaffodil(i))
cout<<i<<" ";
cout<<endl;
return;
}
void main(void)
{
NaturalNumber nn;
nn.setValue (6);
cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素數" <<endl;
nn.setValue (37);
cout<<nn.getValue()<<(nn.isPrime()?"是":"不是")<<"素數" <<endl;
nn.setValue (84);
cout<<nn.getValue()<<"的因子有:";
nn.printFactor();
nn.setValue (29);
cout<<nn.getValue()<<"的因子有:";
nn.printFactor();
nn.setValue (6);
cout<<nn.getValue()<<(nn.isPerfect()?"是":"不是")<<"完全數" <<endl;
nn.setValue (37);
cout<<nn.getValue()<<(nn.isPerfect()?"是":"不是")<<"完全數" <<endl;
nn.setValue (1237);
int x=732;
cout<<nn.getValue()<<" 和"<<x<<" "<<(nn.isReverse(x)?"是":"不是")<<"逆向數" <<endl;
cout<<"所有大於,且小於數據成員"<<nn.getValue()<<" 的水仙花數有:";
nn.printDaffodils();
system("PAUSE");
}