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.

df

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!

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
429762337057011941556865358029
(taken from here https://bigprimes.org/) and let us know what happens and why...

Taifun

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.

5 Likes

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 :

2 Likes

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...

Taifun

2 Likes

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
            break;
1 Like