I changed the question in the post. Please see above.
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
Last edited by Benjamin; 18-12-2023 at 13:05. Reason: Changed subject
I changed the question in the post. Please see above.
Last edited by Benjamin; 18-12-2023 at 13:41.
I simplified the logic, but still got 36,560, which the Euler Project says is incorrect.
What gives?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
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, 32 bits wide , up to 4294967295dim total as dword
Try this version:
RegardsUses "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
DC
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
Benjamin
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
www.thinbasic.com | www.thinbasic.com/community/ | help.thinbasic.com
Windows 10 Pro for Workstations 64bit - 32 GB - Intel(R) Xeon(R) W-10855M CPU @ 2.80GHz - NVIDIA Quadro RTX 3000
Bookmarks