testing number primality using regular expression

Share your advanced PureBasic knowledge/code with the community.
applePi
Addict
Addict
Posts: 1404
Joined: Sun Jun 25, 2006 7:28 pm

testing number primality using regular expression

Post by applePi »

i feel i should post this even i can't follow how it works since i have a severe Sore throat, it is about using regular expressions to check primality of numbers. look here
http://www.noulakaz.net/weblog/2007/03/ ... e-numbers/
http://montreal.pm.org/tech/neil_kandalgaonkar.shtml

it will work for small numbers but not for a number like 1234567891 or 123456781 it will say it is prime even it is composite, this is because the capacity of string variable or the engine itself.
feel free to change it or to explain how it works

Code: Select all

number=13
sNum.s = LSet("1", number,"1") ; make string from 13 "1"'s
 
CreateRegularExpression(0, "^1?$|^(11+?)\1+$")
a = MatchRegularExpression(0, sNum) 
If a =0 
  Debug ("number = " + number + "  is prime")
Else
  Debug ("number = " + number + "  is not prime")
EndIf  
User avatar
STARGÅTE
Addict
Addict
Posts: 2235
Joined: Thu Jan 10, 2008 1:30 pm
Location: Germany, Glienicke
Contact:

Re: testing number primality using regular expression

Post by STARGÅTE »

this method is very slow to check a prime number.

the regular expression works like this:
13 wrote: 1.1111111111 = "1" -> false
11.11.11.11.11.11.1 = "11"*n -> false
111.111.111.111.1 = "111"*n -> false
1111.1111.1111.1 = "1111"*n -> false
...
15 wrote: 111111111111111 = "1" -> false
11.11.11.11.11.11.1 = "11"*n -> false
111.111.111.111 = "111"*n -> true
...
It is tested whether the number is divisible by 2,3,4,5, etc.
PB 6.01 ― Win 10, 21H2 ― Ryzen 9 3900X, 32 GB ― NVIDIA GeForce RTX 3080 ― Vivaldi 6.0 ― www.unionbytes.de
Lizard - Script language for symbolic calculations and moreTypeface - Sprite-based font include/module
davido
Addict
Addict
Posts: 1890
Joined: Fri Nov 09, 2012 11:04 pm
Location: Uttoxeter, UK

Re: testing number primality using regular expression

Post by davido »

Hi applePi,

Thank you for a very interesting post! :D

It'll be a fun way of learning Regular Expressions.
DE AA EB
Post Reply