How to check prime numbers?

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.

  1. Create some project
  2. 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 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.

Set FLG to 0 otherwise it'll show the message 'Not a prime number' even if it's a prime number!

All is ready!


Thank you! Further improvements are always welcome!

Feel free to reply!

You don't explain what a prime number is in your tutorial.

1 Like

Explained it!! :slight_smile:

Try your solution with a large number like
(taken from here and let us know what happens and why...


1 Like

The rational square root of a rational number, if any, is the largest factor of that number that is less than itself. So to scan prime numbers, it's enough to take the square root of a number, and that will reduce our trading volume tremendously. Thanks for your sharing. I've improved a bit what I learned from you.


It will simply crash the app.

Because of the For Each block and the procedure isn't meant to calculate such large prime numbers.

Use Goldbach's Conjecture:

Or you can provide some good approach to cover very large number aswell. Example :


You forgot to mention, that there is such a restriction with your tutorial...
What about providing a solution, which also works for large numbers?
Tip: try alogic, which uses a clock component to avoid the runtime error...



Also, in this traditional approach aswell,
you may break the loop if you found out number is divisible by something..

FOR i = 2 TO (n-1) DO
    IF(n%i == 0) THEN
        FLG = 1
1 Like