Results 1 to 4 of 4

Thread: Help with Script

  1. #1
    Join Date
    Mar 2009
    Location
    Antaractica, Penguin Drive
    Posts
    140
    Mentioned
    0 Post(s)
    Quoted
    0 Post(s)

    Default Help with Script

    Ok, so I'm working on a script to find the factors of a given number and then print them out. Everything seems to work except that it always leaves out a couple factors. If anyone can help then thanks

    SCAR Code:
    program New;

    function IsDecimal(x, y:integer): Boolean;
    var z: integer;
    begin
      z := x / y;
      if x mod y = 0 then
      begin
        Result := True;
      end else
        Result := False;
    end;
     
    procedure FindFactors(x:integer);
    var
    i, z, h, m:integer;
    Factors: array of Integer;
    begin
      for i:=1 to x do
      begin
      z := i;
        if IsDecimal(x, z) then
        begin
          h := Length(Factors);
          m := h + 1;
          SetLength(Factors, m);
          Factors[High(Factors)] := z;
          i := i + 1;
        end;
      end;
      for i:=0 to High(Factors) do
      begin
        WriteLn(Factors[i]);
      end;
    end;

    begin
      FindFactors(100);
    end.

  2. #2
    Join Date
    Mar 2007
    Posts
    3,042
    Mentioned
    1 Post(s)
    Quoted
    14 Post(s)

    Default

    Remove the line

    SCAR Code:
    i := i + 1;

    from your code and everything should work as intended.
    :-)

  3. #3
    Join Date
    Mar 2009
    Location
    Antaractica, Penguin Drive
    Posts
    140
    Mentioned
    0 Post(s)
    Quoted
    0 Post(s)

    Default

    Ok thanks. I haven't scripted in a while so I wasn't sure if it did that by default XD I've been javascripting at school to annoy people must've got i++ stuck in my head >.>

    Anyway thanks

  4. #4
    Join Date
    Oct 2006
    Posts
    500
    Mentioned
    0 Post(s)
    Quoted
    0 Post(s)

    Default

    I cleaned and shortened your code. Should work as you want now:

    Code:
    program Factors;
    
    function IsDecimal(x, y: Integer): Boolean;
    begin
      Result := (x mod y) = 0;
    end;
    
    procedure FindFactors(x: Integer);
    var
      i, ii: Integer;
      Factors: array of Integer;
    begin
      for i := 1 to x do
      begin
        if IsDecimal(x, i) then
        begin
          ii := Length(Factors) + 1;
          SetLength(Factors, ii);
          Factors[ii - 1] := i;
        end;
      end;
      for i := 0 to High(Factors) do
        WriteLn(Factors[i]);
    end;
    
    begin
      FindFactors(100);
    end.
    The problem was i := i + 1; The for loop increments i for you

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •