Search code examples
mit-scratchperfect-square

How do I display all perfect squares below a given number on scratch?


I was able to list all the prime numbers up to an inputted number, however as I am inexperienced at coding on Scratch, I have had difficulty constructing a list of all the perfect squares below a number. For example, if you input 17 the output should be 16,9,4.


Solution

  • The main way to detect if a number is a perfect square is to take the square root and round it and then multiply it by itself. If it is a perfect square the answer will be the number you started with.

    Let's try with 4: The square root of 4 is 2 and when you round it you get 2 and when you multiply 2 times 2 you do get 4 so 4 is a perfect number.

    Let's try with 5: The square root of 5 is 2.23606797749979 and when you round it you get 2 and when you multiply 2 times 2 you do NOT get 5.

    There are two ways to write the loop: you can count up or you can count down. Either way, for each number you do the test and if the number is a perfect square you display it.

    counting down: counting down

    counting up: counting up