0

I'm currently writing a code the takes a number given a prints all the prime numbers that fit the format 4n+1. This is what I have so far. They problem is that this gives me a runtime error 207 which I think means invalid floating point operation, but I can't see how it ended up doing an invalid floating point operation. The only the code should be dealing with negative numbers in the line "if num-(iter*iter)> then".

program TwoSquares;

var
    num, numSqrt, iter, bigSqr,smallSqr: integer;
    


begin
    num:=29;
    
    while num>4 do
    begin
        numSqrt:=trunc(sqrt(num));
        for iter:=2 to numSqrt do
        begin
            if num mod iter = 0 then
                num:=num - 1;
                continue;
        end;
        
        if (num-1) mod 4 = 0 then
        begin
            iter:=(num-1) div 4;
            while iter>0 do
            begin
                if num-(iter*iter)>0 then
                    bigSqr:=iter;
                    break;
                iter:=iter-1;
            end;
            smallSqr:=trunc(sqrt(num-(iter*iter)));
            writeln(num,' ', smallSqr,' ',bigSqr);
            num:=num - 1;
        end;
    end;
end.
  • 1
    Single step your program and you will find the error. Taking the square root of a negative number is the cause of the invalid floating point operation. Yet, you don't test for negative numbers before executing `smallSqr:=trunc(sqrt(num-(iter*iter)));` So there is a flaw in your prime number test and you need to work it out. Best way is learn basic debugging techniques. – LU RD Oct 28 '20 at 09:15
  • Another good technique for simple problems like this one is to write out the values of all relevant variables at the head of each loop. – 500 - Internal Server Error Oct 28 '20 at 09:46

1 Answers1

0

Your check is not directly before the place where it is used. Think; is the break; statement after that num-(iter*iter) if-then check the only way that while loop can terminate?

Try to single step your program, this can also verify if the block structure works as you think. It doesn't seem very consistent, with begin..end in some places, and indentation in others.

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89