基础代码--数学基础
·最大公约数
·最小公倍数
·素数判定与筛法素数表
·生成全排列
·生成全组合
·求组合数
·进制转换
1.求最大公约数
Function gcd(a,b:longint):longint;
Begin
if a mod b=0 then exit(b)
else exit(gcd(b,a mod b));{辗转相除法}
End;
2.求最小公倍数
Function lcm(a,b:longint):int64;
Var
t:int64;
Begin
if a<b then begin t:=a;a:=b;b:=t;end;
t:=a;
while t mod b<>0 do inc(t,a);{连续累加大数直至能被小数整除}
exit(t);
End;
3.判断素数
Function prime(num:longint):boolean;
Var
k:longint;
Begin
if num<2 then exit(false);
for k:=2 to trunc(sqrt(num)) do
if num mod k=0 then exit(false);
exit(true);
End;
4.筛法求素数表
Procedure del_number;
Var
i,t:longint;
Begin
h[1]:=false;
for i:=2 to maxn do
begin
if h[i] then
begin
t:=i+i;
while t<=maxn do
begin
h[t]:=false;
t:=t+i;
end;
end;
end;
End;
Procedure rec_prime;
Var
i,k:longint;
Begin
k:=0;
for i:=2 to maxn do
if h[i] then
begin
inc(k);
p[k]:=i;
end;
p[0]:=k;
End;
5.用表判断素数
Function prime(x:longint):boolean;
Var
i:Longint;
Begin
for i:=1 to p[0] do
if p[i]>x then break
else if x mod p[i]=0 then exit(false);
exit(true);
End;
6.生成全排列
Procedure pl(dep:longint);
Var
i:longint;
Begin
if dep=n+1 then
begin
write(a[1]);
for i:=2 to n do
write(' ',a[i]);
writeln;
exit;
end;
for i:=1 to m do
if not used[i] then
begin
used[i]:=true;
a[dep]:=i;
pl(dep+1);
used[i]:=false;
end;
End;
7.生成全组合
Procedure zh(dep:longint);
Var
i:longint;
Begin
if dep=n+1 then
begin
write(a[1]);
for i:=2 to n do
write(' ',a[i]);
writeln;
exit;
end;
for i:=a[dep-1] to m do
begin
if not used[i] then
begin
used[i]:=true;
a[dep]:=i;
zh(dep+1);
used[i]:=false;
end;
end;
End;
8.求组合数
Procedure make;
Var
i,j:longint;
Begin
for i:=1 to m do
begin
c[i,0]:=1;
c++判断素数 c[i,1]:=i;
c[i,i]:=1;
end;
for i:=2 to m do
for j:=2 to n do
begin
if j>i then break;
c[i,j]:=c[i-1,j]+c[i-1,j-1];
end;
End;
9.进制转换
将十进制数n转换为k进制数
Program TenToK;
Const
num:array[0..35]of char=('0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
Var
n,k:longint;
a:array[0..200]of integer;
Procedure change(n,k:longint);
Var
i:longint;
Begin
fillchar(a,sizeof(a),0);
i:=0;
while n>0 do
begin
inc(i);
a[i]:=n mod k;
n:=n div k;
end;
a[0]:=i;
for i:=a[0] downto 1 do
write(num[a[i]]);
writeln;
End;
Begin
readln(n,k);
change(n,k);
End.
将K进制数转换为十进制数
Program KToTen;
Var
i,j,len,k,t,ans:longint;
s:string;
a:array[0..100]of integer;
Begin
readln(k);
readln(s);
len:=length(s);
for i:=1 to len do
begin
if (s[i]>='0')and(s[i]<='9') then a[len-i+1]:=ord(s[i])-ord('0')
else if (s[i]>='A')and(s[i]<='Z') then a[len-i+1]:=ord(s[i])-ord('A')+10
else if (s[i]>='a')and(s[i]<='z') then a[len-i+1]:=ord(s[i])-ord('a')+10
end;
ans:=0;
for i:=1 to len do
begin
t:=1;
for j:=1 to i-1 do
t:=t*k;
ans:=ans+a[i]*t;
end;
writeln(ans);
End.
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论