How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Forth programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Forth programming language

Table of Contents

Problem Statement

The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below n. Show output for n = 1000. This is is the same as Project Euler problem 1. Extra credit: do this efficiently for n = 1e20 or higher.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sum multiples of 3 and 5 step by step in the Forth programming language

Source code in the forth programming language

: main ( n -- )
  0 swap
  3 do
    i 3 mod 0= if
      i +
    else i 5 mod 0= if
      i +
    then then
  loop
  . ;

1000 main    \ 233168  ok


: third  2 pick ;

: >dtriangular ( n -- d )
    dup 1+ m* d2/ ;

: sumdiv ( n m -- d )
    dup >r / >dtriangular r> 1 m*/ ;

: sumdiv_3,5 ( n -- n )
    dup 3 sumdiv third 5 sumdiv d+ rot 15 sumdiv d- ;

: euler1 ( -- n )
    999 sumdiv_3,5 drop ;

: euler1tower ( -- )
    1  \ power of 10
    19 0 DO
        cr dup 19 .r space dup 1- sumdiv_3,5 d.
        10 *
    LOOP drop ;

euler1 . 233168  ok
euler1tower 
                  1 0 
                 10 23 
                100 2318 
               1000 233168 
              10000 23331668 
             100000 2333316668 
            1000000 233333166668 
           10000000 23333331666668 
          100000000 2333333316666668 
         1000000000 233333333166666668 
        10000000000 23333333331666666668 
       100000000000 2333333333316666666668 
      1000000000000 233333333333166666666668 
     10000000000000 23333333333331666666666668 
    100000000000000 2333333333333316666666666668 
   1000000000000000 233333333333333166666666666668 
  10000000000000000 23333333333333331666666666666668 
 100000000000000000 2333333333333333316666666666666668 
1000000000000000000 233333333333333333166666666666666668  ok


  

You may also check:How to resolve the algorithm Strip control codes and extended characters from a string step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Resistor mesh step by step in the Wren programming language
You may also check:How to resolve the algorithm Middle three digits step by step in the C programming language
You may also check:How to resolve the algorithm Split a character string based on change of character step by step in the Pascal programming language
You may also check:How to resolve the algorithm String matching step by step in the NewLISP programming language