Today we will learn about checking prime numbers, in App Inventor. It is possible to check, without any APIs and extensions. Let's start!
A prime number is a number that is only divisible by 1 and the number itself.
- Create some project
- Structure (not design) should be like this:
Don't forget to make textbox Numbers Only, because it will throw an error when user types text instead of number!
Let's move on to blocks!
First, we declare a Boolean-typed flagging variable, with value of 0. I called it FLG.
We'll not use True / False blocks for better understanding.
Next, we add a For block in button1.click or any other button.
We are starting from 2, because it is the first prime number. But 1 is also but it isn't considered.
We are writing Textbox1.text minus 1 because it is the best way to check, and also if we enter a non-prime number, it will say accordingly since it is divisible by the loop.
Next we add an if then block inside that For loop!
We will be checking the remainder of Textbox1.txt รท The loop number
If 0, then it is not prime, and FLG is set to 1.
Now the final part! If FLG is 0 then show it's prime else not prime.
!!! VERY IMPORTANT !!!
Set FLG to 0 otherwise it'll show the message 'Not a prime number' even if it's a prime number!
All is ready!
Output
Thank you! Further improvements are always welcome!
Feel free to reply!