算法竞赛入门——因子和阶乘
来源:互联网 发布:dota后期三大核 知乎 编辑:程序博客网 时间:2024/06/05 02:15
输入正整数n(2<=n<=100),吧阶乘n!=1*2*3*4*…*n分解诚因子想成的形式,从小到大输出各个素数(2、3、/5…)的指数。例如825=3*5^2*11应该表示成(0,1,2,0,1),表示分别有0、1、2、0、1个2、3、5、7、11。你的程序应忽略比最大素因子更大的素数。输入样例:553输出样例:5!=3 1 153!=49 23 12 8 4 4 3 2 2 1 1 1 1 1 1 1
代码如下:
#include <iostream>#include <stdio.h>#include <stdlib.h>#include <math.h>#include <string.h>using namespace std;int is_prime(int x){ for (int i = 2; i<=sqrt(x); i++) if (x%i == 0) return 0; return 1;}int main(){ int n, a[100], b[100]; while (cin >> n) { memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); int Count = 0; for (int i = 2; i <= n; i++) { if (is_prime(i)) a[Count++] = i; } for (int i = 1; i<=n; i++) { int m = i; for (int j = 0; j<Count; j++) { while (m%a[j] == 0) { m /= a[j]; b[j]++; } } } cout << n << "!="; int x; for (x = Count; x >= 0; x--) if (b[x]) break; for (int i = 0; i<=x; i++) cout << b[i] << " "; cout << endl; } system("pause"); return 0;}
我这里讲素数模板放到了while函数里面,无疑增加了运算量,因此,为减少运算量,直接将素数模板放到while函数外面,讲循环次数调整一下就可以。如下:
#include <iostream>#include <stdio.h>#include <stdlib.h>#include <math.h>#include <string.h>using namespace std;int is_prime(int x){ for (int i = 2; i<=sqrt(x); i++) if (x%i == 0) return 0; return 1;}int main(){ int n, a[100], b[100]; int Count = 0; for (int i = 2; i <= 100; i++) { if (is_prime(i)) a[Count++] = i; } while (cin >> n) { memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); for (int i = 1; i<=n; i++) { int m = i; for (int j = 0; j<Count; j++) { while (m%a[j] == 0) { m /= a[j]; b[j]++; } } } cout << n << "!="; int x; for (x = Count; x >= 0; x--) if (b[x]) break; for (int i = 0; i<=x; i++) cout << b[i] << " "; cout << endl; } system("pause"); return 0;}
阅读全文
0 0
- 算法竞赛入门——因子和阶乘
- 算法竞赛入门经典5.4.2因子和阶乘
- 算法竞赛入门经典 第五章 因子和阶乘
- 算法入门竞赛 5.4.2 因子和阶乘
- 算法竞赛入门经典-第五章因子和阶乘
- 算法竞赛入门经典:第五章 基础题目选解 5.10 因子和阶乘
- 【py交易】算法竞赛入门经典5.4.2 因子和阶乘 Python
- 算法——因子和阶乘
- 算法入门之因子和阶乘
- 算法竞赛入门——阶乘的精确值
- 因子和阶层~算法竞赛入门(基础篇-5.4.2)
- 因子和阶乘
- 因子和阶乘
- 因子和阶乘
- 白皮书&&因子和阶乘
- 因子和阶乘
- 因子和阶乘
- 因子和阶乘
- C# String与StringBuilder
- js Tree 简单使用例子
- VS2017上执行VS2013项目错误MSB802之解决方案
- Mapreduce模型
- Android ActionBar应用实战,高仿微信主界面的设计
- 算法竞赛入门——因子和阶乘
- 矩阵乘法与运用
- [KMP+矩阵快速幂加速]BZOJ 1009——[HNOI2008]GT考试
- 第一章:1.2.2系统分类(一)
- CSS, JavaScript, jQuery实现标签页切换
- 安装包cmake后可否删除源文件?
- H5知识点
- 20170814_深度探索C++对象模型
- QT中QWidget、QDialog及QMainWindow的区别