- 任何一个合数都可以写成几个质数相乘的形式。请编写程序分解质因数(以下各题皆假设用户输入都是合法的数据,即不考虑非法输入)。
const int maxn = 10010;
bool is_prime(int n) {
if (n <= 1) {
return false;
}
int sqr = sqrt(1.0 * n);
for (int i = 2; i <= sqr; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int prime[maxn], pNum = 0;
void Find_Prime() {
for (int i = 1; i < maxn; i++) {
if (is_prime(i)) {
prime[pNum++] = i;
}
}
}
int main() {
int n;
Find_Prime();
while (scanf("%d", &n) != EOF) {
int sqr = sqrt(1.0 * n);
int num[maxn], t = 0;
for (int i = 0; i < pNum && prime[i] <= sqr; i++) {
if (n % prime[i] == 0) {
while (n % prime[i] == 0) {
num[t++] = prime[i];
n = n / prime[i];
}
}
if (n == 1) {
break;
}
}
if (n != 1) {
num[t++] = n;
}
for (int i = 0; i < t - 1; i++) {
printf("%d * ", num[i]);
}
printf("%d\n", num[t - 1]);
}
return 0;
}
- 显示倒杨辉三角,请严格按如下示例形式输入和输出。
int main() {
int n;
while (scanf("%d", &n) != EOF) {
int a[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i; j++) {
if (j == 0) {
a[i][j] = 1;
} else if (i == j) {
a[i][j] = 1;
} else {
a[i][j] = a[i - 1][j - 1] + a[i - 1][j];
}
}
}
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < n - i - 1; j++) {
printf(" ");
}
for (int j = 0; j <= i; j++) {
printf("%4d", a[i][j]);
}
printf("\n");
}
}
return 0;
}
- 把m个同样的苹果放在n个同样的盘子里,允许有的盘子空着不放,问共有多少种不同的分法? 5,1,1和1,5,1 是同一种分法。(递归思想:https://blog.csdn.net/u012283461/article/details/52761238)
int getcount(int apple, int plant) {
if (apple == 0 || plant == 1) {
return 1;
}
if (plant > apple) {
return (apple, apple);
} else {
return getcount(apple, plant - 1) + getcount(apple - plant, plant);
}
}
int main() {
int m, n;
while (scanf("%d %d", &m, &n) != EOF) {
printf("%d\n", getcount(m, n));
}
return 0;
}
- 输入一个小数(double类型存储),格式化成货币形式存储于一个字符数组中,并输出, 前面加$,整数每3位加逗号,小数点后保留两位。
#include <iostream>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
using namespace std;
const int maxn = 10010;
char ans[50];
int main() {
double n;
while (scanf("%lf", &n) != EOF) {
int flag = 0, t = 3;
long x, small;
x = n * 100 + 0.5;
small = x % 100;
ans[0] = small % 10 + '0';
small = small / 10;
ans[1] = small % 10 + '0';
ans[2] = '.';
x = x / 100;
while (x != 0) {
ans[t++] = x % 10 + '0';
flag++;
if (flag == 3 && x / 10 != 0) {
ans[t++] = ',';
flag = 0;
}
x = x / 10;
}
ans[t++] = '$';
for (int i = t - 1; i >= 0; i--) {
printf("%c", ans[i]);
}
printf("\n");
}
return 0;
}
-
编写程序,输入x、y的值,按如下公式计算并显示z的值(小数点保留两位显示z)
公式图
const int maxn = 10010;
char ans[50];
const double PI = acos(-1.0);
int main() {
double x, y;
while (scanf("%lf %lf", &x, &y) != EOF) {
double ans;
if (y > 0) {
double fz = abs(sqrt(x));
double fm = 5 + 2 * y;
ans = fz / fm;
} else if (x < 0 && y < 0) {
ans = sin(35 / 180 * PI) - 6 * x + y * y;
} else if (x > 0 && y < 0) {
ans = pow(y, x) - 2;
} else {
printf("error!\n");
continue;
}
printf("%.2f\n", ans);
}
return 0;
}
网友评论