[笔试题]比较两个阶乘的大小

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

[笔试题]⽐较两个阶乘的⼤⼩
此题⽬的意思是:形如下⾯的两个字符串阶乘,判断哪个更⼤。

12 和 3。

前者有4个阶乘号,后者有5个。

利⽤的原理就是:越⼤的数的同阶阶乘越⼤。

也就是阶乘的单调性。

所以可以直接去掉相同个数的阶乘号后再作⽐较。

没有写⼤整数类,所以请不要⽤剩余两个!!以上的数测试,会溢出。

下⾯是主要函数的代码:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
long long factorial( string& str )
{
int excl = count( str.begin(), str.end(), '!' );
string temp = str.substr( 0, str.size() - excl );
long long number = atoi( temp.c_str() );
for ( int i = 0 ; i < excl ; i++ )
{
long long t = 1;
for( long long k = 1 ; k <= number ; k++ )
{
t *= k;
}
number = t;
}
cout<<"The value of longer number cut off is : "<<number<<endl;
cout<<"----------------"<<endl;
return number;
}
//return 1 if a > b. else return -1
int compare(string& a, string& b)
{
int excl_a = count( a.begin(), a.end(), '!');
int excl_b = count( b.begin(), b.end(), '!');
int excl = min( excl_a, excl_b );
//cut off exclamation
string aa = a.substr( 0, a.size() - excl );
cout<<"The first number cut off is : "<<aa<<endl;
string bb = b.substr( 0, b.size() - excl );
cout<<"The second number cut off is : "<<bb<<endl;
cout<<"-------------"<<endl;
//without exclamation
if ( aa.find( '!', 0 ) != string::npos ) //exclamation in aa
{
long long first = factorial( aa );
long long second = atoi( bb.c_str() );
if ( first > second )
return 1;
else
return -1;
}
else//no exclamation in aa
{
long long first = factorial( bb );
long long second = atoi( aa.c_str() );
if ( first > second )
return -1;
else
return 1;
}
}
下⾯是测试的主函数:
int main()
{
string a( "12" );
cout<<"The first number is : "<<a<<endl;
string b( "3" );
cout<<"The second number is : "<<b<<endl;
cout<<"------------"<<endl;
cout<<a<<" "<<( ( compare( a, b ) > 0 ) ? ">" : "<" )<<" "<<b<<endl; cout<<endl<<endl;
string c( "6" );
cout<<"The first number is : "<<c<<endl;
string d( "500!!" );
cout<<"The second number is : "<<d<<endl;
cout<<"------------"<<endl;
cout<<c<<" "<<( ( compare( c, d ) > 0 ) ? ">" : "<" )<<" "<<d<<endl; }。

相关文档
最新文档