Pascal / Python因数分解程序

时间:2018-08-26 15:30:29

标签: python pascal factorization

我制作了两个程序来查找数字的素因,一个在python中,一个在pascal中。我想分解为600851475143; python程序立即将其分解。但是,pascal不能在合理的时间内完成。它与其他编程语言有关还是我在Pascal中如何编码?我在python中使用了递归,而在pascal中则没有使用。为什么pascal程序也不能立即完成?

python:

<?php wp_footer(); ?>
</body>
</html>

帕斯卡:

def findLowestFactor(num, factors=None):
    if factors:
        start = factors[-1]
    else:
        start = 2
    for i in range(start, int(num)):
        if num%i == 0:
            return i
    else:
        return False


def findPrimeFactors(num, factors=None):
    if factors is None:
        factors = []
    factor = findLowestFactor(num, factors)
    if factor:
        factors.append(factor)
        findPrimeFactors(num/factor, factors)
        return factors
    else: 
        factors.append(int(num))
        return factors


if __name__ == "__main__":
    while True:
        num = int(input("Please enter a number: "))
        factors = findPrimeFactors(num)
        print(*factors)

1 个答案:

答案 0 :(得分:4)

我将您的Python代码翻译为Pascal。我使用了Delphi,但它也应该在FreePascal中进行编译。它立即返回:

type
  TIntArray = array of Integer; // Delphi: TArray<Integer>;

function findLowestFactor(num: Int64; factors: TIntArray): Integer;
var
  start: Integer;
  i: Int64;
begin
  if Length(factors) > 0 then
    start := factors[High(factors)]  // factors[-1] in Python, i.e. last entry.
  else
    start := 2;
  i := start;
  while i < num do        // Int64 can not be used as index in for-loop... 
  begin                   // ... so I use while loop.
    if num mod i = 0 then // Python: if num % i == 0:
      Exit(i);            // return i
    Inc(i);
  end;
  Exit(0);
end;

procedure findPrimeFactors(num: Int64; var factors: TIntArray);
var
  factor: Integer;
begin
  factor := findLowestFactor(num, factors);
  if factor > 0 then
  begin 
    // Delphi: factors := factors + [factor];
    SetLength(factors, Length(factors) + 1);
    factors[High(factors)] := factor;

    findPrimeFactors(num div factor, factors);
  end
  else
  begin
    // Delphi: factors := factors + [Integer(num)];
    SetLength(factors, Length(factors) + 1);
    factors[High(factors)] := Integer(num);
  end;
end;

const
  testValue: Int64 = 600851475143;

var
  factors: TIntArray;
  i: Integer;
  result: Int64;

begin
  // Instead of user input, I use the testValue above.
  Writeln('test value: ', testValue);
  findPrimeFactors(testValue, factors);
  result := 1;
  for i in factors do
  begin
    Write(i:8);
    result := result * i;
  end;
  Writeln;
  Writeln('multiplied: ', result);
  Readln;
end.

请注意,我必须在某些地方使用Int64 。我认为Python是自动执行此操作的,而不是Pascal。也许在某些地方使用Integers会使您的代码如此缓慢。

我省略了代码的用户输入部分(Readln等),只是使用了您提供的常量值。但是,正如我所说,它会立即以正确的值返回(请参见可变结果)。