c++训练题(牵扯到大数据的保存)

题目:The 5-digit number, 16807=7^5, is also a fifth power. Similarly, the 9-digit number, 134217728=8^9, is a ninth power. How many n-digit positive integers exist which are also an nth power?

题目的大概意思是7的5次方为16807,是一个5位数;同样8的9次方134217728也是一个9位数。求有多少类似n次方刚好是n位数的数字存在。

分析:1的1次方是1为1位数。1的2次方为1为1位数(不符合)。

   2的1次方是2为1位数。2的2次方为4为1位数(不符合)。

           3的1次方是3为1位数。3的2次方为9为1位数(不符合)。

           4的1次方是4为1位数。4的2次方为16为2位数。4的3次方为64为2位数(不符合)。

           一直到10,10的一次方为10为2位数,不符合条件。

从中我们可以得出这样的条件:1.满足底数条件的数字范围在1~9。2.底满足条件的n次方是连续的,从小到大的,不存在在n次不满足条件,n+1次满足条件的情况。

这个程序的难点不在于怎么算,而在于9的21次方已经超过了long long 的范围,容易出错,需要跳过整数类型来进行运算。

方法1,用log10来计算幂指数

// test.cpp : 定义控制台应用程序的入口点。
//判断有多少n位整数同时使另一个数的n次幂存在
//例如16807=7^5,16807是5位数,同时使7的5次幂。同理,134217728=8^9
//分析得知,需要一个判断正整数为几位数的子函数

#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	double n;
	int count=0;
	for(int i=1; i<10; i++)
	{
		n=1;
		//ostringstream os;
		//bool flag=true;
		while(int(log10(pow(i,n))+1)==n)
		{
			cout<<i<<"的"<<n<<"次幂"<<pow(i,n)<<"满足要求!"<<endl;
			++n;
			++count;
		}
	}
	cout<<"共有"<<count<<"个整数满足要求!"<<endl;
	system("pause");
	return 0;
}
方法2 用STL标准库的字符串来存储大数据,计算位数

// test.cpp : 定义控制台应用程序的入口点。
//判断有多少n位整数同时使另一个数的n次幂存在
//例如16807=7^5,16807是5位数,同时使7的5次幂。同理,134217728=8^9
//分析得知,需要一个判断正整数为几位数的子函数

#include "stdafx.h"
#include <iostream>
#include <sstream>
#include <string>
#include <cmath>
using namespace std;
int Digit(string num)
{
	int Len=num.length();
	//stringstream ss;
	return Len;
	//while((num/pow(10.0,n))>=1)
	//{
	//	++n;
	//}
}
int _tmain(int argc, _TCHAR* argv[])
{
	double n;
	int count=0;
	for(int i=1; i<10; i++)
	{
		n=1;
		ostringstream os;
		/*bool flag=true;*/
		while(true)
		{
			//int temp=pow(i,n);
			os.setf(ios::fixed);
			os<<pow(i,n);
			string str=os.str();
			int pos=str.find_first_of('.');
			string num=str.substr(0,pos);
			int s=Digit(num);
			os.clear();
			os.str("");
			if(s!=n)
			{
				//flag=false;
				break;
			}
			cout<<i<<"的"<<n<<"次幂"<<pow(i,n)<<"满足要求!"<<endl;
			++n;
			++count;
		}
	}
	cout<<"共有"<<count<<"个整数满足要求!"<<endl;
	system("pause");
	return 0;
}
结果:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值