1. [问题1]:考虑由1到n(n<=9)按递增顺序排成的序列12345…n,在他们之间加入加号、减号和空格,分别使它们作加法、减法和将数字合并。然后求出结果,看看你是否得到零。程序找出所有长度为n的结果为零的序列。
程序如下:
ar n:vord
a:array[1..9]of byte;
procedure init;
begin
write(‘enter n:’);
readln(n);
a[n]:=1;
end;
procedure print;
const s:array[1..3]of string=(‘+’,‘ ’,‘-’);
var i:word;
begin
for i:=1 to n-1 do
write(i,s[a[i]]);
writeln(n,’=0’);
end;
procedure judge;
var i,ch:integer;
result,term:longint;
begin
result:=0;
ch:=1;
term:=1;
for i:=1 to n do
case a[i] of
1,3:begin result:=result+(2-ch)*term;
ch:=a[i];
term:=i+1;
end;
2:term:=term*10+i+1;
end;
if result=0 then print;
end;
procedure find(k:word);
var i:word;
begin
if k=n then judge
else
for i:=1 to 3 do
begin
a[k]:=i
find(k+1);
end;
end;
begin
init;
find(1);
end.
2. [问题2]:整数n的阶乘写作n !,它是从l到n的所有整数的乘积。阶乘增长的速度很快:13!在大多数计算机上不能用32位的整数来存放。70!已经超出多数浮点类型的范围。你的任务是找出n!最右边的非零位。例如,5!=1*2*3*4*5=120,所以5!的最右非零位为2,同样,7!=1* 2*3*4*5*6* 7=5040,所以7!的最右非零位为4。
输入:一个在1~1000的整数n。
输出:n !的最右非零位。
程序如下:
const max=250;
var a:array[1..max+1]of word;
n:word;
procedure init;
begin
write(‘enter n:’);
readln(n);
fillchar(a,sizeof(a),0);
a[1]:=1;
end;
procedure calc;
var i,j;word;
begin
for i:=2 to n do 或for i:=1 to n do
begin
for j:=1 to max do
a[j]:=a[j]*i;
for j:=1 to max do
begin
inc(a[j+1],a[j]div 10);
a[j]:=a[j]mod 10;
end;
end;
end;
procedure print;
var i:word;
begin
i:=j;
while a[i]=0 do
inc(i);
writeln(a[i]);
end;
begin
init;
calc;
print;
end.
3. [问题3]:考虑在0和1之间的所有分母不大于N的最简分数。下面是N=5时的情况:
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 l/1
程序对于一个给定的整数N(1<=N<=100),按从小到大的顺序打印出这些
分数。还应打印出它们的总数。在每个分数后面打印一个制表符,使他们在显示的时
候一行不会很长。
要求:当N<1或N>100时,程序应判错。
举例:
enter the maximum demominator:5
0/1 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 l/1
there are 11 fractions.
程序如下:
type denominator=array[1..2] of byte;
var a: array[1..10000] of denominator;
n,num:word;
procedure init;
begin
repeat
write(‘enter the maximum denominator:’);
readln(n);
if not(n in[1..100]) then writeln(‘input error!);
until n in [1..100];
num:=0;
end;
procedure calc;
var i,j;word;
mid:denominator;
procedure add(x,y:word);
var k:word;
begin
for k:=2 to y do
if(x mod k=0)and(y mod k=0)then exit;
inc(num);
a[num,1]:=x;
a[num,2]:=y;
end;
begin
for i:=2 to n do
for j:=1 to i-1 do
add(i,j);
for i:=1 to num do
for j:i+1 to num do
{ if(a[i,1]*a[j,2]<a[i,2]*a[j,1])then 或if (a[i,2]/a[i,1]>a[j,2]/a[j,1]) then }
begin
mid:=a[i];
a[i]:=a[j];
a[j]:=mid;
end;
end;
procedure print;
var i:word;
begin
write(‘0/1’,#9);
for i:=1 to num do
write(a[i,2],’/’,a[i,1],#9);
writeln(‘1/1’,#9);
writeln(‘there were’,num+2,’fractions.’);
end;
begin
init;
calc;
print;
end.