|| 返回 || 本站首页 ||奥赛信息||计算机基础||pascal基础||数据结构||经典算法||试题汇编||校本教程||自主练习||

|| 自主练习>> 把自然数N分解为若干个自然数之积、和

双击自动滚屏 

   

   

【题目】把自然数N分解为若干个自然数之积
【参考程序】
var  path :array[1..1000] of integer;
     total,n:integer;
procedure find(k,sum,dep:integer);     {K:}
var b,d:Integer;
begin
     if sum=n then                       {积等于N}
      begin
               write(n,'=',path[1]);
               for d:=2 to dep-1 do write('*',path[d]);
               writeln;inc(total);
               exit;
      end;
    if sum>n then exit;                         {累积大于N}
    for b:= trunc(n/sum)+1 downto k do               {每一种可能都去试}
               begin
                      path[dep]:=b;
                      find(b,sum*b,dep+1);
               end;
end;
 
begin
readln(n); total:=0;
find(2,1,1);writeln('total:',total);
readln;

end.

 

【题目】把自然数N分解为若干个自然数之和
【参考答案】
                         n     │ total  

                         5        7
                         6       11
                         7       15
                              10       42
                              100      190569291
 【参考程序】
var n:byte; num:array[0..255] of byte;               total:word;
 procedure output(dep:byte);
var j:byte;
begin
     for j:=1 to dep do write(num[j]:3);writeln;    inc(total);
end;
 procedure find(n,dep:byte);  {N:待分解的数,DEP:深度}
  var i,j,rest:byte;
  begin
     for i:=1 to n do              {每一位从N到1去试}
      if num[dep-1]<=i then   {保证选用的数大于前一位}
       begin
                num[dep]:=i;
                rest:=n - i;               {剩余的数进行下一次递归调用}
                if (rest>0) then begin   find(rest,dep+1);end
                             else if rest=0 then output(dep);{刚好相等则输出}
                num[dep]:=0;
       end;
  end;
 
begin  {主程序}
   writeln('input n:');readln(n);
   fillchar(num,sizeof(num),0);
   total:=0; num[0]:=0;
   find(n,1);
   writeln('sum=',total);

end.

 

 
 

 

 
 
 

制作与维护:重庆市忠县中学 谭海