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

本文介绍了一种比较带有多个阶乘符号的字符串大小的方法。利用阶乘的单调性,通过去除相同数量的阶乘符号简化比较过程。代码实现采用C++,并提供了具体的函数和测试案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

此题目的意思是:形如下面的两个字符串阶乘,判断哪个更大。

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;
}





转载于:https://www.cnblogs.com/microgrape/archive/2011/05/11/2043801.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值