2005年上机题
题目一:把一个数表示成若干个素数的和
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
bool isPrime(int n);
void divideNum(int n);
int count = 0;
int main()
{
divideNum(201);
system("pause");
}
bool isPrime(int n)
{
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i <= sqrt((double)(n)); i++) {
if (0 == n%i) {
return false;
}
}
return true;
}
void divideNum(int n)
{
if (isPrime(n)) {
if (count == 0) {
printf("n=%d", n);
count++;
}
else {
printf("+%d", n);
}
}
else
{
for (int i = n / 2; i >= 2; i--) {
if (isPrime(i)) {
if (count == 0) {
printf("%d=%d", n, i);
count++;
}
else {
printf("+%d", i);
}
divideNum(n - i);
break;
}
}
}
}
题目二:统计篇文章中各英文字母的个数,并排序
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
struct Character
{
int count = 0;
char c;
};
int main()
{
FILE *f1 = fopen("D:\\test.txt", "r");
if (f1 == NULL) {
printf("FILE OPEN ERROR!");
exit(1);
}
Character c[26];
int max;
Character temp;
for (int i = 0; i < 26; i++) {
c[i].c = i + 'a';
}
char a;
while ((a = getc(f1)) != EOF) {
if (a >= 'a' && a <= 'z') {
c[a - 'a'].count++;
}
if (a >= 'A' && a <= 'Z') {
c[a - 'A'].count++;
}
}
for (int i = 0; i < 25; i++) {
max = i;
for (int j = i + 1; j < 26; j++) {
if (c[max].count < c[j].count)
max = j;
}
if (max != i) {
temp.c = c[max].c;
temp.count = c[max].count;
c[max].c = c[i].c;
c[max].count = c[i].count;
c[i].c = temp.c;
c[i].count = temp.count;
}
}
for (int i = 0; i < 26; i++) {
printf("%c: %d\n", c[i].c, c[i].count);
}
fclose(f1);
system("pause");
return 0;
}
2006年上机题
题目一:找出100到1000内的不含9的素数,存到result文件中。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
bool isPrime(int n);
bool haveNine(int n);
void main()
{
FILE * fp = fopen("result.txt", "w");
if (fp == NULL) {
printf("FILE OPEN ERROR!\n");
exit(1);
}
for (int i = 100; i < 1001; i++) {
if (isPrime(i) && !haveNine(i)) {
fprintf(fp, "%d\n", i);
}
}
fclose(fp);
}
bool isPrime(int n)
{
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i < sqrt((double)(n))+1; i++) {
if (0 == n%i) {
return false;
}
}
return true;
}
bool haveNine(int n)
{
while (n != 0) {
if (9 == n % 10) {
return true;
}
n = n / 10;
}
return false;
}
2007年上机题
题目一:把10到1000之间满足以下两个条件的数,存到result.txt文件中
(1)是素数。
(2)它的反数也是素数,如:123的反数是321。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
bool isPrime(int n);
int reverse(int n);
void main()
{
FILE *fp = fopen("result.txt", "w");
if (fp == NULL) {
printf("FILE OPEN ERROR!\n");
exit(1);
}
for (int i = 100; i < 1001; i++) {
if (isPrime(i) && isPrime(reverse(i))) {
fprintf(fp, "%d\n", i);
}
}
fclose(fp);
}
bool isPrime(int n)
{
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i < (sqrt((double)(n)) + 1); i++) {
if (0 == n%i) {
return false;
}
}
return true;
}
int reverse(int n)
{
int m = 0;
while (n != 0) {
m = m * 10 + n % 10;
n = n / 10;
}
return m;
}