上得厅堂,下得厨房,写得代码。翻得围墙,欢迎来到睿不可挡的每日一小练!
题目:因子分解
内容:编写一个程序,读入一个正整数,把它的全部质因子找出来。比如输入的181944,181944=2^3x3^2x7x19^2,
所以质因子为2,3,7,19。
我的解法:上来没多想,打开vs2013就敲了起来,问题果然非常easy。分分钟就超神。。奥,不正确就攻克了!非常easy的一道题目,就是使用有技巧的连除,将数学思想转换为程序。
#include <iostream>
#define MaxNum 1000
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int n,finalNum;
int i, j;
int Num[MaxNum] = { 0 };
int count[MaxNum] = { 0 };
int ct = 0;
cout << "请输入一个整数:" << endl;
cin >> n;
finalNum = n;
for (i = 0;(n % 2 == 0) && n > 1;n/=2 ,i++);
Num[ct] = 2;
count[ct++] = i;
for (j = 3; j <= n; j += 2)
{
for (i = 0;( n%j == 0 )&& n > 1; n/= j, i++);
Num[ct] = j;
count[ct++] = i;
}
cout << finalNum << "能够分解成质因子为:";
int temp = 0;
while (temp < ct)
{
if (count[temp] != 0)
{
cout << " "<< Num[temp] << "^" << count[temp] << " ";
if (temp + 1 != ct)
{
cout << "x";
}
}
temp++;
}
getchar();
getchar();
return 0;
}
实验结果为
欢迎大家增加每日一小练,嘿嘿!
每天练一练。日久见功夫,加油。
-End-
參考文献:《c语言名题精选百则》