PDA

View Full Version : Two Consoles



Benjamin
18-12-2023, 12:35
The first problem for the Euler Project is as follows:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5. 6. and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

So I wrote the code below, which gives 36,560. The Euler Project says this answer is incorrect. Can someone give me a hint about what's wrong? I honestly can't see it.


USES "Console"
DIM i AS Integer
DIM Total AS Word VALUE 0

FOR i = 1 TO 999

IF MOD(i, 3) = 0 THEN
Total += i
ELSEIF MOD(i, 5) = 0 THEN
Total += i
END IF

NEXT

CONSOLE_WRITELINE Total
WAITKEY

Benjamin
18-12-2023, 12:49
I changed the question in the post. Please see above.

Benjamin
18-12-2023, 13:56
I simplified the logic, but still got 36,560, which the Euler Project says is incorrect.


USES "Console"
DIM i AS Integer
DIM Total AS Word VALUE 0

FOR i = 1 TO 999

IF MOD(i, 3) = 0 OR MOD(i, 5) = 0 THEN
Total += i
END IF

NEXT

CONSOLE_WRITELINE Total
WAITKEY


What gives?

dco045
18-12-2023, 20:12
Hi Benjamin

The variable total is declared word

Word is 16 bits numbers from 0 to 65535

when i reaches 528 total is 65103 and for i = 530 total wraps to 97 instead of 65633

Use
dim total as dword , 32 bits wide , up to 4294967295


Try this version:


Uses "Console"
DIM i AS Integer
DIM Total AS word VALUE 0
DIM total_dw AS dword VALUE 0

FOR i = 1 TO 999

IF MOD(i, 3) = 0 OR MOD(i, 5) = 0 THEN

Total += i
total_dw += i
printl i, total, total_dw
END IF
if i = 530 then WaitKey 'pause
NEXT

CONSOLE_WRITELINE Total , total_dw
PrintL "Press a key to end program"

'---Wait for a key press
WaitKey


Regards

DC

Benjamin
19-12-2023, 00:28
Hi DC,

Thanks so much for the detailed explanation. I learned a trick with those two variables. I'll have to remember that. Believe it or not, the first time I wrote it, I used Integer, but when I got a negative number, I knew I had wrapped around.

I'm relieved to know that I'm not losing my mind :D

Benjamin

ErosOlmi
24-12-2023, 12:46
To store numbers it is better to always use DWORD, LONG or QUAD for integer numbers and DOUBLE or EXT (EXTENDED) for floating point numbers.
Leave all other numeric data types for compatibility with data structure you need to use or external functions (DLLs) that specifically require them.

Even when you just need a simple counter for a loop, better to use LONG/DWORD.
They are much faster because native 32bit