求:设有一整数X,通过算法算出它是否能被另一个数N(不等于1和它自己)整除,如果能,则求出最大的N是多少?
求该算法,可能很菜!答对给分!

解决方案 »

  1.   

    for i := (x-1)downto 1 do
    begin
    if xmodi=0 then
      result := i:
      break;
    end;
      

  2.   

    用两个一维数组
    例如:a[1..N]{n-->+无穷大}
          b[1..N]
    a[1] a[2] a[3]...a[N]   
    /
    b[1] b[2]  b[3] ...b[N]
    分别存放数字进行运算。
      

  3.   

    //如果只考虑自然数,可以这样改进一下idilent的方法function MaxFactor(X: Cardinal; var aMaxFactor: Cardinal): Boolean;
    var
      X2,
      Factor: Cardinal;
    begin  
      if X > 4 then
        X2 := X div 2
      else if X = 4 then
      begin
        aMaxFactor := 2;
        Result := True;
        Exit;
      end
      else
      begin
        Result := False;
        Exit;
      end;
        
      for Factor := X2 downto 2 do
        if (X mod Factor) = 0 then
        begin
          aMaxFactor := Factor;
          Result := True;
          Exit;
        end;  Result := False;
    end;
      

  4.   

    //更高速的function MaxFactor2(const X: Cardinal; var aMaxFactor: Cardinal): Boolean;
    var
      X2, vMaxFactor, Factor, Quotient, Remainder: Cardinal;
    begin
      if X > 4 then
        X2 := X div 2
      else if X = 4 then
      begin
        aMaxFactor := 2;
        Result := True;
        Exit;
      end
      else
      begin
        Result := False;
        Exit;
      end;  vMaxFactor := 0;
      Factor := 2;  while True do
      begin
        asm
          xor EDX, EDX
          mov EAX, X
          div EAX, Factor
          mov Quotient, EAX
          mov Remainder, EDX
        end;    if Remainder = 0 then
        begin
          if Factor < Quotient then aMaxFactor := Quotient
          else aMaxFactor := Factor;
          Result := True;
          Exit;
        end;    if Factor = X2 then Break;
        Inc(Factor);
      end;
      Result := False;
    end;
      

  5.   

    //吃饱了又想到一个更快的,未测试function MaxFactor3(const X: Cardinal; var aMaxFactor: Cardinal): Boolean;
    var
      X2, Factor, Quotient, Remainder: Cardinal;
    begin
      if X > 3 then
      begin
        if X and 1 = 0 then
        begin
          Result := True;
          aMaxFactor := X shr 1;
          Exit;
        end
        else
        begin
          X2 := X shr 1;
          Factor := 3;
          repeat
            asm
     xor edx, edx
     mov eax, X
     div eax, Factor
     mov Quotient, eax
     mov Remainder, edx
            end;        if Remainder = 0 then 
            begin
     aMaxFactor := Quotident;
     Result := True;
     Exit;
            end;
            Inc(Factor, 2);
          until Factor > X2;
        end;
      end
      else
        Result := False;
    end;