1

在我必须说这个之前:请原谅我的英语不好...我是学生。我的老师给了我课程作业的帕斯卡问题...我必须编写计算 2^n 的程序来计算 n 的大值...我已经写了但是有一个问题...我的程序对于大于 30 的 n 值返回 0...我的代码在下面...请帮助我:::Thanks 先...

function control(a: integer): boolean;
var 
   b: boolean;
begin
   if (a >= 10) then b := true
   else b := false;

   control := b;
end;

const
   n = 200000000;

var
   a: array[1..n] of integer;
   i, j, c, t, rsayi: longint; k: string;

begin
   writeln('2^n');
   write('n=');
   read(k);

   a[1] := 1;
   rsayi := 1;
   val(k, t, c);

   for i := 1 to t do
   for j := 1 to t div 2 do
   begin
      a[j] := a[j] * 2;
   end;

   for i := 1 to t div 2 do
   begin
      if control(a[j]) = true then
      begin
         a[j + 1] := a[j + 1] + (a[j] div 10);
         a[j] := a[j] mod 10;
         rsayi := rsayi + 1;
      end;
   end;
   for j := rsayi downto 1 do write(a[j]);
end.
4

2 回答 2

1

The first (nested) loop boils down to "t" multiplications by 2 on every single element of a.

30 multiplications by two is as far as you can go with a 32-bit integer (2^31-1 of positive values, so 2^31 is out of reach)

So the first loop doesn't work, and you probably have to rethink your strategy.

于 2013-05-09T10:27:17.200 回答
0

这是一个快速而肮脏的程序,用于计算所有 2^n 直到某个给定的可能很大的 n。程序反复将数组 a 中的数字加倍,以 10 为底存储;a[1] 中的低位数字。请注意,它并不是特别快,因此在 n = 200000000 时使用它是不明智的。

program powers;

const
   n = 2000;   { largest power to compute }
   m = 700;    { length of array, should be at least log(2)*n }

var
   a: array[1 .. m] of integer;
   carry, s, p, i, j: integer;

begin
   p := 1;
   a[1] := 1;
   for i := 1 to n do
   begin
      carry := 0;
      for j := 1 to p do
      begin
         s := 2*a[j] + carry;
         if s >= 10 then
         begin
            carry := 1;
            a[j] := s - 10
         end
         else
         begin
            carry := 0;
            a[j] := s
         end
      end;
      if carry > 0 then
      begin
         p := p + 1;
         a[p] := 1
      end;
      write(i, ': ');
      for j := p downto 1 do
         write(a[j]);
      writeln
   end
end.
于 2013-05-10T10:09:21.373 回答