73939133 - Probably the Most Interesting Prime Number [Part 2][PyMath #2]

  Рет қаралды 14,536

Flammable Maths

Flammable Maths

Күн бұрын

The Math behind: • 73939133 - Probably th...
PyMath Playlist: • PyMath
Today we code a program that spits out a list of all possible right truncatable Prime Numbers and thus, also the biggest one in existence 73939133. Truncatable primes are numbers, such that you can take the last digit off and still receive a prime number again :)
This video is part of the MegaFavNumbers project. Maths KZbinrs have come together to make videos about their favourite numbers bigger than one million, which we are calling #MegaFavNumbers.
We want you, yes you humble viewer, to join in! Make your own video about your favourite mega-number. You can think of a cool big number, or think of a cool topic first and hang a mega-number on it. Upload your videos to KZbin with the hashtag #MegaFavNumbers and with MegaFavNumbers in the title, and your video will be added to the megafavnumbers playlist.
Submit your videos anytime before Wednesday 2nd September to be added to the MegaFavNumbers playlist! MegaFavNumbers Playlist: • MegaFavNumbers
Python Code:
import math
def primalitytest(y):
for i in range(2, math.floor(math.sqrt(int(y)))+1):
if (int(y) % i) == 0:
break
else:
return y
def trunc(x):
trunclist = ['2','3','5','7']
trunclistnew = ['2','3','5','7']
appendlist = ['1','3','7','9']
trigger = True
while trigger == True:
trigger= False
length=len(trunclist)
for i in range(0, len(trunclist)):
for j in range(0, len(appendlist)):
primecand = trunclist[i]+appendlist[j]
for t in range(2, math.floor(math.sqrt(int(primecand)))+1):
if (int(primecand) % t) == 0:
break
else:
trunclistnew.append(primecand)
trunclist.append(primecand)
for i in range(0,length):
trunclist.pop(0)
trigger = True
if len(trunclist)==0:
biggest = trunclistnew[len(trunclistnew)-1]
print('The biggest truncatable prime number is',str(biggest)+'.')
trigger = False
print('')
print('The list of all right truncatable primes is: ')
return(trunclistnew)
a = input('You sure u wanna see the biggest niBBa? ')
print('')
print(trunc(a))
Help me create more free content! =)
/ mathable
Merch :v - papaflammy.myt...
www.amazon.com...
shop.spreadshi...
Become a Member of the Flammily! :0 / @papaflammy69
2nd Channel: / @npcooking69
--------------------------------------------------------------------------------
Wanna send me some stuff? lel:
Postfach 11 15
06731 Bitterfeld-Wolfen
Saxony-Anhalt
Germany
--------------------------------------------------------------------------------
My Website: papaflammy.eng...
Instagram: / uncomfortably_cursed_m...
Flammy's subreddit: / flammybois
Twitter: / flammablemaths
Facebook: / flammablemaths
Got some time to spare? Make sure to add captions to my videos! =) www.youtube.com...
Want to know more about me? Watch my QnA! =D • Question and Answer Ti...

Пікірлер: 147
@NPCooking69
@NPCooking69 4 жыл бұрын
Hey you there! :D Thanks for watching! Make sure to watch the other part of the video too kzbin.info/www/bejne/a3OpdZeMpqZ5kKc and to subscribe to this channel as well as Flammable Maths Two if you haven't done so already and enjoyed what you've witnessed here today! :D
@Burkieeee
@Burkieeee 4 жыл бұрын
Some of this program is written with a serious C++/Java "accent". My maths undergrad taught coding through C++ and I had to unlearn a lot when I started with python, so maybe you're in the same boat ¯\_(ツ)_/¯ You can directly refer to the elements of an iterable as you iterate over it, so "for i in list_of_numbers" means your "i"s are the numbers, no need for the ranges or indexing (which feel very boilerplatey and C-ish). Also since lists are sliceable, the pop loop isn't needed, you just want trunclist = trunclist[length:]. You don't need equality tests for the booleans here, and if you did you'd use the keyword "is" rather than ==, so it'd be "if trigger:" or "if trigger is True", but not "if trigger == True". (the difference between the two is checking for explicit boolean True vs checking for any Truthy value ie not False or None or [] etc.). Also the len in trunclistnew[len(trunclistnew)-1] is redundant since you've just made sure that its length is 0 (You could also have checked "if not trunclist:" since the empty list is Falsey). Some of the looping could probably be made neater using the itertools package / list comprehension / generator expressions as well. But yeah, idk, they're worth a look if you're coming from a different language since there might not be an equivalent and they're neat. tl;dr: This python needs to go to the vet
@xoriun8638
@xoriun8638 4 жыл бұрын
Your first two points work in Java/C++ as well, but I agree that this ain't really nice code. Eg. he could have set the trigger to true, when he detects a prime number, if there is none, trigger stays on false.
@Ricocossa1
@Ricocossa1 4 жыл бұрын
As a C++ maniac, I see a lot of stuff in this code that needs improving and that is not simply python illiteracy. But I learnt a few things from this, so thank you very much. :) In C++, what comes after the 'if' has to be a boolean expression. If it isn't, it gets converted. So you can absolutely write stuff like 'if (bool)' or 'if (!vector.size())' C++ even allows you to define your own (implicit) type conversion operators for your classes, with a member function named: operator bool() const {your code; return bool; } (the 'const' simply ensures that no members of the class are modified) (There is a blank space in the function's name, however weird that looks)
@mprone
@mprone 4 жыл бұрын
Papa is great at math. Papa needs to improve his python though
@minerscale
@minerscale 4 жыл бұрын
He used IDLE. Stop making fun of disabled people.
@duncanw9901
@duncanw9901 4 жыл бұрын
No one: Flammy: if cond: break Flammy: while bool==True:
@feynman6756
@feynman6756 4 жыл бұрын
@@minerscale What exactly is wrong with IDLE mister?
@minerscale
@minerscale 4 жыл бұрын
@@feynman6756 I hate it because it looks really ugly and lacks all the features I'd want in my text editor. Personally I use sublime-text for all of my programming needs and I love it, the build systems, the lovely UI, *the speed*, and lately, git integration. I mean heck, line numbers are considered an 'advanced feature' and need to be turned on in IDLE. I guess it's usable but it's insanely clunky. It's written in python tkinter, anyone who's used python tkinter understands why this program sucks.
@discretelycontinuous2059
@discretelycontinuous2059 4 жыл бұрын
@@duncanw9901 ye
@jfr9964
@jfr9964 4 жыл бұрын
hey if anyone wants a more elegant pythonic solution using recursion, here you go. is_prime(n) is any primality test function def f(n): if is_prime(n): P.add(n) for d in {1, 3, 7, 9}: f(10 * n + d) P = set() for n in [2, 3, 5, 7]: f(n) print(f"LIST: {list(sorted(P))} MAX: {max(P)}")
@PositronQ
@PositronQ 4 жыл бұрын
jfr I think more elegant in the form of the size . The mathematicians think in other way the programming like flammble math
@cheshire1
@cheshire1 4 жыл бұрын
@@PositronQ I personally find the recursive code more elegant, but if you want a solution with a set of candidates that still have to be evaluated, here you go: def trunc(): closedSet = set() openSet = {2, 3, 5, 7} appendices = {1, 3, 7, 9} while openSet: x = openSet.pop() closedSet.add(x) for a in appendices: candidate = 10*x + a if is_prime(candidate): openSet.add(candidate) return(closedSet)
@Daniel-nl3ug
@Daniel-nl3ug 4 жыл бұрын
Why is P a set here? Are sets faster for sorting or something?
@ezioarno15
@ezioarno15 4 жыл бұрын
Python is generally terrible for recursion. i do agree finding it the recursive way is more elegant and pure.
@1ich_mag_zuege
@1ich_mag_zuege 4 жыл бұрын
Here is my code. import math def p(n): if n==1: return(False) for i in range(2,1+math.floor(math.sqrt(n))): if n%i==0: return(False) return(True) numbers=[""] while numbers!=[]: j=numbers[0] for k in range(1,10): if p(int(j+str(k))): numbers.append(j+str(k)) numbers.remove(j) print(j)
@copperfield42
@copperfield42 4 жыл бұрын
Flammy being bad/new at python trigger me XD
@ChongFrisbee
@ChongFrisbee 4 жыл бұрын
True trigger? Or a False trigger? Hard to tell those apart at this point
@copperfield42
@copperfield42 4 жыл бұрын
​@@ChongFrisbee more into the true trigger, his prime testing function show in the video is just plain wrong (not to mention that doesn't return a boolean which would be more proper for a prime testing function), and later he goes a copy the code of that into the other function, if you make it a function, call it and no copy paste its code into other places... and that is just the general stuff, there is also the more python specific, like iterating over a range of the len of some list instead of the list, and soo on... some can be forgiven by being new...
@ChongFrisbee
@ChongFrisbee 4 жыл бұрын
@@copperfield42 , look closely at the assignments on the `trigger` variable. That will make the joke clearer. I somehow forgot about Poe's law and didn't emoji it up. My bad
@3ckitani
@3ckitani 4 жыл бұрын
Fun fact: 694201337 is a prime number, and it's made of 69, 420, and 1337 Edit: #MegaFavNumbers
@ebentually
@ebentually 4 жыл бұрын
in your function to check for primes such a while loop: while i**2 < k: check for prime i += 1 might be better for larger numbers as this avoids computing the square root of k
@scavengerethic
@scavengerethic 4 жыл бұрын
This must be the first time I've seen for/else used in Python, and it's extra special that it was done accidentally and accidentally happened to remove a bug that existed when the else was still indented for the if it originally came from. This is art.
@TheJamesM
@TheJamesM 4 жыл бұрын
I was so puzzled by that when he first wrote the function. I thought "surely this can't work", but me being an occasional coder at best, I assumed he knew something I didn't. I did notice the difference in indentation when he pasted it (which was in itself a bit of an odd move...).
@thomhughes4617
@thomhughes4617 4 жыл бұрын
ye its a weird feature but super nice, i found out about it on stackoverflow when trying to make some logic neater with nested for loops. stackoverflow.com/questions/189645/how-to-break-out-of-multiple-loops
@nHans
@nHans 4 жыл бұрын
Coding interview questions: (1) Modify the above program to find (a) Left-truncatable Prime Numbers, (b) Left-and-right truncatable Prime Numbers (2) Enhance your program to find truncatable prime numbers (L/R/L-R) in any base. (3) Identify the algorithm used in the original program (e.g. BFS, DFS, ...) (4) Rewrite using the alternative algorithm (That is, if Flammable Math used BFS, rewrite using DFS and vice-versa). Math interview question: Prove, without running the program, that the number of such primes are finite.
@COZYTW
@COZYTW 4 жыл бұрын
>when both parts of the video are exactly 16 minutes 57 seconds long and you end up trying to find part 2 five times
@HurricaneEmily
@HurricaneEmily 4 жыл бұрын
1657 is prime, FYI.
@chrisdooph5092
@chrisdooph5092 4 жыл бұрын
For anyone interested: Right truncateable: 73 939 133 Left truncateable: 357 686 312 646 216 567 629 137 Right-left (alternating) truncateable: 889 292 677 731 979 Left-Right (alternating) truncateable: 8 313 667 333 393 I calculated these with Mathematica, cause my python skill are non-existent. 😅
@amaarquadri
@amaarquadri 4 жыл бұрын
In my opinion, the best thing to learn to improve Python programming is list comprehension. It can make generating the next iteration of candidates into a one-liner. Here's my code: from math import sqrt, ceil def is_prime(n): if n == 2 or n == 3: return True if n < 5 or n % 2 == 0 or n % 3 == 0: return False # check divisibility by numbers that are equal to 1 mod 6 or 5 mod 6. # This avoids redundancy with checking divisibility mod 2 and divisibility mod 3. for k in range(1, ceil((sqrt(n) + 1) / 6)): if n % (6 * k - 1) == 0 or n % (6 * k + 1) == 0: return False return True def generate_right_truncatable_primes(): candidates = [n for n in range(10) if is_prime(n)] digits = [1, 3, 7, 9] results = [] while len(candidates) > 0: new_candidates = [] for candidate in candidates: longer_candidates = [n for n in [10 * candidate + d for d in digits] if is_prime(n)] if len(longer_candidates) == 0: results.append(candidate) else: new_candidates += longer_candidates candidates = new_candidates return sorted(results) if __name__ == '__main__': print(generate_right_truncatable_primes()[-1])
@kittenhero568
@kittenhero568 4 жыл бұрын
oh boy, this is like watching a mathematician code
@philippelepilote7946
@philippelepilote7946 4 жыл бұрын
The first time I feel better than Papa !
@aldobernaltvbernal8745
@aldobernaltvbernal8745 4 жыл бұрын
papa needs to improve his python
@tylerfusco7495
@tylerfusco7495 4 жыл бұрын
faster primality check (uses the AKS method): def is_perfect_power(n: int) -> bool: """ tests if n is a perfect power. e.g: is_perfect_power(125) -> True is_perfect_power(69) -> False """ # O(log(n)) for i in range(2, ceil(log2(n))+1): root = n ** (1/i) if round(root)==root: return True return False def is_prime(n: int) -> bool: """ Uses the AKS primality check to see if a number is prime. Complexity: O(log(n)^7) """ if n==2: return True if n%2==0: return False if is_perfect_power(n): return False def get_r(n: int) -> int: l = log2(n) max_k = floor(l*l) max_r = max(3, ceil(l ** 5)) next_r = True r = 2 while (next_r and r < max_r): next_r = False k = 1 while not next_r and k < max_k: next_r = pow(n, k, r) in (0, 1) k = k + 1 r = r + 1 return r - 1 r = get_r(n) if n
@e2298sg
@e2298sg 4 жыл бұрын
You should use a queue instead of your "first" list. It does what you want way more cleanly and efficiently. The stop condition should be checked in the while statement, so instead of "while triggrer", just do "while len(first) != 0". Negative indexes are valid in python, so "tlistnew[-1]" will give you the las element. For primality checking, you can just check if it's divisible by 2, then only check divisibility by odd numbers. You can go one step further, and use the fact that every prime number greater than 3 is either 1 or 5 mod 6, so you only need to check those. Also please, for the love of god, use numbers when you want numbers, not strings. To append a digit to a number, just multiply it by 10 and add the digit.
@coolcat5018
@coolcat5018 4 жыл бұрын
As a mathematician doing cpsc courses at uni, I can see the same excitement I had when learning python for the first time. These are some tips I have to offer after taking a couple classes: - break up complex functions into a couple of smaller functions. For example, you defined a primality test beforehand, so you could use a similar function to replace a chunk in your code by calling it inside of trunc(x). It is not recommended to copy and paste the same lines of code in your script because of semantic coupling (making changes in one area of code requires you to make changes in another area of code) - set up a github account + download github desktop, so you can show off all your math / algorithmic ideas to your subscribers. - download a text editor. This offers error + keyword highlighting and autocomplete features. I use Atom and I installed the hydrogen plugin inside the settings to have the quality of life features (download platformio-ide-terminal to have a terminal inside of atom). You could also just use visual studio code or whatever. - here's your code after I made some minor changes (didnt have time to go too deep into it): www.overleaf.com/read/txjhvqgdtrwn
@loukafortin6225
@loukafortin6225 4 жыл бұрын
That "Yes ! *Clap*" was so genuine it was satisfying
@ChongFrisbee
@ChongFrisbee 4 жыл бұрын
Trigger: False Code:... More code:... Trigger: True, definetly True Trigger: no, wait: False, it's False now
@sovietcat919
@sovietcat919 4 жыл бұрын
papa is such a Chad knows both programming and maths
@tinu5779
@tinu5779 4 жыл бұрын
def rtp(): rtp = [ 2, 3, 5, 7 ] digits = ( 1, 3, 7, 9 ) i = 0 while i < len(rtp): for digit in digits: p = rtp[i] * 10 + digit if is_prime( p ): rtp.append( p ) i += 1 return rtp
@achampion
@achampion 4 жыл бұрын
You can use a generator: def rtp(): q = [2, 3, 5, 7] while q: p = q.pop() yield p for d in (1, 3, 7, 9): # n = 10*p+d Py = 3.8 q.append(n) max(rtp()) # 73939133
@tinu5779
@tinu5779 4 жыл бұрын
@@achampion Nice improvement, thanks :)
@alcesmir
@alcesmir 4 жыл бұрын
Generators and recursion is fine in this case and makes the thing quite nice and clean: def rtp_expand(n): yield n for i in [1,3,7,9]: p = n*10 + i if is_prime(p): yield from rtp_expand(p) def rtp(): yield from (x for n in [2,3,5,7] for x in rtp_expand(n)) print(sorted(rtp()))
@strengthman600
@strengthman600 4 жыл бұрын
Great video! This inspired me to write some code that does this in any given base, not just 10
@darylewalker6862
@darylewalker6862 4 жыл бұрын
Now I’m curious about generalizing this to any integer radix of at least 3. The starting numbers are all the primes less than the radix. The extension digits are all the positive integers less than the radix that are relatively prime to it.
@p0gr
@p0gr 3 жыл бұрын
thats the most efficient algorithm you could find? the naive primality test? interesting.
@cubernetes
@cubernetes 4 жыл бұрын
I think this is one of the most compact codes for this problem, 248 characters and it simply prints all right truncatable primes. Any ideas on how to make it shorter are appresciated! def p(n): if sum(list(map(lambda x:1if n%x==0else 0,range(2,int(n**.5)+1))))
@spy8514
@spy8514 4 жыл бұрын
Should we ignore that the primality test fails?
@pauliunknown8118
@pauliunknown8118 4 жыл бұрын
everyone in the comments complaining about coding style..... this is why i don't hang out with cmp sci people smh fam
@PapaFlammy69
@PapaFlammy69 4 жыл бұрын
It actually annoys me really hard these days. I had a lot of fun programming in the last time, but this really ruins it for me atm :(
@heisenberg4703
@heisenberg4703 4 жыл бұрын
@@PapaFlammy69 at least for me, that was not my intention. I wanted to give you some tips, like you do for me in maths. You'll get better with time, like with anything. We(people commenting on your coding style) went through it all and wanted to make it less shit. I don't know how to else describe the 'beginning' of coding.
@alcesmir
@alcesmir 4 жыл бұрын
@@heisenberg4703 It's all a matter of giving actionable feedback. "Your code is shit" is dumb and not helpful. "This thing is dumb, you can do it in this nicer way: " is actually actionable and useful for learning.
@heisenberg4703
@heisenberg4703 4 жыл бұрын
@@alcesmir lol I didn't say his code was shit, I said that the beginning of programming was shit. I actually submitted my tidied version of his code
@alcesmir
@alcesmir 4 жыл бұрын
​@@heisenberg4703 Not directed at you. More in response to this: > We(people commenting on your coding style) went through it all and wanted to make it less shit. I saw quite some people just shitting on the code and not given any actionable critique at all, which is not helpful and just comes off as condescending.
@kuba-xz3rl
@kuba-xz3rl 4 жыл бұрын
Here is my C++ solution: vector list = { 2, 3, 5, 7 }; vector append = { 1, 3, 7, 9 }; int i = 0; bool end = false; while (!end) { int n = list.size(); for (int j = i; j < n; j++) for (auto k : append) { int p = 10 * list[j] + k; if (prime(p)) list.push_back(p); } i = n; if (n == list.size()) end = true; }
@akshat9282
@akshat9282 4 жыл бұрын
your pt(x) function is incorrect. it only checks for division by 2 and either breaks or returns the number. try pt(9) or any odd number.
@akshat9282
@akshat9282 4 жыл бұрын
instead of break, use return False and change the program accordingly
@gabriel7233
@gabriel7233 4 жыл бұрын
@@akshat9282 He wrote the else statement outside the loop and somehow it worked lol
@akshat9282
@akshat9282 4 жыл бұрын
@@gabriel7233 it would but only if he returned instead of breaking
@akshat9282
@akshat9282 4 жыл бұрын
i tried replicating this right now because I was doubting myself and not papa. but no, the test in his vid and description both don't work correctly for primality
@gabriel7233
@gabriel7233 4 жыл бұрын
@@akshat9282 idk how did you run it but I copied the code from the description and it worked for me. I'm not very comfortable with python but I found that apparently there are for/else statements(which is really weird lol) and that's how it worked. Also papas solution is imo very messy and unclear and using queue(and the function which he implemented and didn't use which is also weird) he could've reduced those 4 nested loops to only 2.
@arcannite6152
@arcannite6152 4 жыл бұрын
5:59 I know this basically does nothing to the efficiency but it's still so ugly that I got TRIGGERed
@roeesi-personal
@roeesi-personal 4 жыл бұрын
I can see you are new to Python and maybe to coding in general, so here is some constructive criticism to help you improve in the future: First and most importantly, please don't copy and paste your code. Functions are a thing for a reason - if you write a function you can call it later in your code instead of copying and pasting its code. Copy pasting your code is much more error prone since if you have an error you need to correct it in all the places you copied it to, but if you only write the code in one function and then call it in other places you need to correct the code only once. Also, functions that test if a number have a certain property (like whether it is a prime or not) can return True and False, and it's a much better and clearer convention than returning the input or returning nothing. Also, Python has a native syntax for truncating lists - indexing with colons. lst[i:j] is the list lst from place i (inclusive) to place j (not inclusive), and you can also leave a slot empty if you want it to start in the beginning of the list or to end in its end. For example, if you need to make the list first only its elements from element number length to its end you can write this: first = first[length:] Deleting the elements from the beginning of the list like you did is relatively inefficient because for every item you delete python needs to shift all of the other elements one place to the right. And if we're talking about python features I really recommend you to read about list comprehension. It's a very powerful tool that allows you to create a short code that does a lot. For example, the body of the function loop could be mostly shortened to this line alone: first = [num + digit for num in first for digit in appendlist if pt(int(num + digit))] making the code much shorter and simpler. Another nice feature of python is that negative indices are interpreted is indices backwards from the end of the list, for example, tlistnew[-1] is equivalent to tlistnew[len(tlistnew) - 1]. Also, it's not recommended to make your function return something with the intention of it being printed. If you print something it's better to just print the whole message and not hope that the function caller will know how to print the end. With these changes and some minor changes, the code of trunc can look like this: def trunc(): first = ['2', '3', '5', '7'] tlistnew = first.copy() appendlist = ['1', '3', '7', '9'] while len(first) > 0: first = [num + digit for num in first for digit in appendlist if pt(int(num + digit))] tlistnew += first biggest = tlistnew[-1] print('...', biggest) # replace the ellipsis with your message, too lazy to copy it. print('...', tlistnew) # same. Then, when calling it probably the best way is to use the variable __name__ that is set to the string '__main__' if your code is run on its own but not when it's imported, like so: if __name__ == '__main__': trunc() Or even better, you can just return tlistnew from the function trunc and print the list and the last element somewhere else - in the main if statement or in another main function that will be called from this statement instead of trunc. Currently this code might not work because in the original version of pt you had a bug that makes it return the input if it passes the first check (i.e. if it's not divisible by 2). You need to change it by putting the else in the same indentation as the for or by deleting the 'else' line entirely and unindenting the line after it so it'll execute only after the for loop if nothing was returned in it. Hope that'll help you and you won't dismiss it as someone trying to just tell you that your code sucks, because I really want to help. You can comment if you didn't understand something or have other coding related questions and I'll be glad to help you improve your coding and python skills.
@623-x7b
@623-x7b 4 жыл бұрын
Wait wouldn't the pt function only check one factor because it has an else with a return statement after the first check?
@Daniel-nl3ug
@Daniel-nl3ug 4 жыл бұрын
It would've done that, but papa did some debugging at 15:20 to fix it I guess.
@sudheerthunga2155
@sudheerthunga2155 4 жыл бұрын
Papa , I literally didn't know of this day ?!? Mann , This is amzing !!!
@sheppsu7353
@sheppsu7353 4 жыл бұрын
Nice video, I went for a recursion approach myself since it felt more elegant. Also programs like PyCharm are better to work in than the default Python IDLE def is_prime(number): for x in range(2, round(number**0.5)+1): if number%x == 0: return False return True def is_trunc(number): for index in range(0, len(number)): if not is_prime(int(number[:len(number)-index])): return False return True TRUNCATED_PRIMES_LIST = [2, 3, 5, 7] def extend_number(number): for num in ['1', '3', '7', '9']: newNum = number+num if is_trunc(newNum): TRUNCATED_PRIMES_LIST.append(int(newNum)) extend_number(newNum) def main(): for number in ['2', '3', '5', '7']: extend_number(number) if __name__ == '__main__': try: main() except KeyboardInterrupt: print("Keyboard Interruption") print(TRUNCATED_PRIMES_LIST) print(len(TRUNCATED_PRIMES_LIST)) print(max(TRUNCATED_PRIMES_LIST))
@alcesmir
@alcesmir 4 жыл бұрын
Code review time! * Why are you representing numbers as strings? It's weird and wasteful. Adding a digit on the right is as easy as `number*10 + digit` * Why do you check if the number is right truncatable(is_trunc) every time in extend number? You know the thing you have is already right truncatable, so you only need to check if adding another digit is still prime. * Have a look at generators in python, they are perfect for this kind of thing (rather than mutating a global variable). * Why wrap the main call in a try?
@sheppsu7353
@sheppsu7353 4 жыл бұрын
@@alcesmir Yeah it would definitely be better for me to just use numbers rather than strings of numbers. To the second point I don't know what I was thinking, I should just have to check if a number is prime with is_prime. To the third point, I hadn't worked very much with generators at the time of making this code so I just used a global list in which to append to. For the third point that's just a habit of mine you could say. The except is for KeyboardInterrupt so if I want to stop my program while it's running I don't have this ugly error message popping up, but just a message saying "Keyboard Interruption" Also thanks for reviewing my code, I'm 14 and I've been working with Python for probably 3 years now
@alcesmir
@alcesmir 4 жыл бұрын
@@sheppsu7353 If you want to see code for this using generators I wrote this: ix.io/2vI8 Might be interesting for learning.
@sheppsu7353
@sheppsu7353 4 жыл бұрын
@@alcesmir ok, thank you, I'll take a look
@AvanaVana
@AvanaVana 4 жыл бұрын
But why is this number the largest right-truncatable prime? That is the interesting question, no?? Edit: I mean is there any deeper reason other than the four possibilities of n=73939133 with any d is an element of {1,3,7,9} appended to n are not prime. It seems counterintuitive that of all possible numbers this becomes impossible only after ~7.4x10^7. There are only 83 RTPs, 4,260 LTPs, and 920,720,315 right- & left-truncatable primes. Is there some property of base 10 that dooms this sequence to an early demise? Are there any bases for which the sequence is infinite? Is this related to the prime number theorem, and the likelihood of the number of primes in any interval as x increases? here is an image of the whole tree of RTPs, btw: i.stack.imgur.com/AiLqY.png
@heisenberg4703
@heisenberg4703 4 жыл бұрын
#My code is nowhere near perfect(Done in 5 minutes lol) and I've not used recursion, but I've tidied up your code a bit: import math def is_prime(n): for i in range(2, math.ceil(math.sqrt(n))+1): if n%i==0: return False return True def trunc(): trunc_set = [2, 3, 5, 7, 9] current_set = [2, 3, 5, 7, 9] while True: length=len(current_set) for i in range(length): for j in {1, 3, 7, 9}: if is_prime(current_set[i]*10+j): trunc_set.append(current_set[i]*10+j) current_set.append(current_set[i]*10+j) current_set=current_set[length:] if len(current_set)==0: return trunc_set trunc_set = trunc() print(f'Amount of rt Primes: {len(trunc_set)} Max value: {max(trunc_set)}') #Feel free to comment suggestions
@alcesmir
@alcesmir 4 жыл бұрын
You might learn something new from my implementation. Generators are fun. Left out the is_prime implementation for clarity (it's the more boring part of the thing). ix.io/2vI8
@HonsW
@HonsW 4 жыл бұрын
# my implementation using list comprehensions and ints trunclist = [2,3,5,7] appendlist = [1,3,7,9] total = [] while trunclist: total += trunclist trunclist = [10*l+r for l in trunclist for r in appendlist if primalitytest(10*l+r)] print(total) # one could use the walrus operator in python 3.8 like trunclist = [pc for l in trunclist for r in appendlist if primalitytest(pc:=10*l+r)]
@Daniel-nl3ug
@Daniel-nl3ug 4 жыл бұрын
If you wanted to use walrus operator you could also do total += (trunclist := etc)
@mr.champion7304
@mr.champion7304 4 жыл бұрын
So, I decided to do this in Common Lisp, since I felt I could do this in a much more elegant way. Especially more elegant than manually inlining functions like he did at 9:50. Before I put the link, though, I want to say that the code doesn't actually produce a list of all right-truncatable primes, it just produces a branching tree like the one shown in the last video. If you don't know what I mean by "branching tree", then I mean that it's a tree where each node is a value of p_(n-1), and whose children are the possible values of p_n given p_(n-1). However, this isn't a tree, but is instead multiple trees(since there are multiple starting nodes, {2,3,5,7}). So, since I needed only one tree, I just let the symbol 'root be the root node(I later changed it to 0 to allow for sorting the flattened tree without needing to take its cdr), and have the starting nodes(the values {2,3,5,7}) be the children of the root node, and then write the function in such a way that it only cares about the given tree's children, and not the root node. Here is the pastebin link to the code "pastebin.com/Y6uPTiVB". In the meantime, I'll try to port some scheme code I wrote for displaying tree structures(in the same format that I did this with) some time ago(for recreational purposes, I was making a little library for manipulating trees) into common lisp, so that I can get a graphical representation of the tree(the code actually translates the tree into a graphviz ".dot" file, and saves it to the disk. With that file, I can use graphviz to render an image of the tree. Is it "hacky"? Sure. But it works for me). EDIT: I ported the code over, ran the code, and got an image of the tree. Here's the link to the image i.ibb.co/FwP1Ft6/rtrunctree.png
@thomhughes4617
@thomhughes4617 4 жыл бұрын
nice! the tree structure in my implementation was the same :)
@HAL-oj4jb
@HAL-oj4jb 4 жыл бұрын
I came to the comments to talk about the code; looks as if I'm not the first one that had this idea :D
@pukkandan
@pukkandan 4 жыл бұрын
Here's a much smaller code for doing the same: def getAllRightTruncatablePrimesFrom(n): test=[10*n+i for i in [1,3,7,9]] return [n, [getAllRightTruncatablePrimesFrom(i) for i in test if isPrime(i)]] print( [getAllRightTruncatablePrimesFrom(x) for x in [2,3,5,7]]) It doesn't print a list, but a tree like structure. You can just flatten it if you need the result as list. Full code: gist.github.com/pukkandan/d2853c687d020bc7c41df379dea1c813
@ffggddss
@ffggddss 4 жыл бұрын
42069 = 3·14023. Not prime. Fred
@PapaFlammy69
@PapaFlammy69 4 жыл бұрын
Sad times :'(
@ffggddss
@ffggddss 4 жыл бұрын
@@PapaFlammy69 And completely factored, it's 42069 = 3·37·379 Successive right truncations of 379, one of your fully right-truncatable primes. So maybe not so sad. :",,] Fred
@AlistairBuxton
@AlistairBuxton 4 жыл бұрын
The number of right-truncatable primes with two or more digits is a right-truncatable prime with two or more digits.
@torment808
@torment808 4 жыл бұрын
learn c++ thank you, jkjk good video
@pteroidea
@pteroidea 4 жыл бұрын
Primality test is broken. Both condition and range are wrong. Condition - it only tests for 2. Range (which does not include the 2nd term) - it fails for any x=square of prime.
@Daniel-nl3ug
@Daniel-nl3ug 4 жыл бұрын
That's what the debugging at 15:20 was for :)
@robyngenn872
@robyngenn872 4 жыл бұрын
Anyone hear that cow die in the beginning.
@brianjamesferguson4646
@brianjamesferguson4646 4 жыл бұрын
what are you saying in the opening moments of the video? very high-pitched, doesn't sound like English
@hambonesmithsonian8085
@hambonesmithsonian8085 4 жыл бұрын
Is it just me or does papa look a lot like the TF2 Scout?
@PapaFlammy69
@PapaFlammy69 4 жыл бұрын
I AM the scout :vvv
@srpenguinbr
@srpenguinbr 4 жыл бұрын
I did it in C++. I'll try pasting it here. #include #include using namespace std; bool prime (int n){ for(int i=2;i
@srpenguinbr
@srpenguinbr 4 жыл бұрын
I wrote the original in Portuguese, so there maybe be some translation error. Note I didn't implement the square root test because I did not want to implement a whole new library for that (and I don't know which has the sqrt function). Also, I'm not certain if performing a square root is worth it in this case, because that is an expensive operation. To be clear, I'm not claiming my version is better, I simply don't know much about computers at a fundamental level, so I kept it simple
@nnniv
@nnniv 4 жыл бұрын
Ayy more python
@SuperMaDBrothers
@SuperMaDBrothers 4 жыл бұрын
while trigger == True 😂😂😂
@fujatv503
@fujatv503 4 жыл бұрын
is there a reason you prefer python over matlab?
@LittlePharma
@LittlePharma 4 жыл бұрын
I can't speak for flammable maths, but the general consensus is that python is much better than matlab for the following reasons: * Matlab is proprietary and closed source. Python is free and open source. * There are a vast number of great libraries for python. As well as the default packages, there are fantastic libraries like numpy, pandas, matplotlib, networkx, tensorflow, django, scipy, pyqt, etc. Numpy especially is extremely performant, being written in highly optimised, parallelised C which makes it faster than matlab at what matlab claims to be great at! * Python is a high level language, allowing you to use it to make a much greater variety of programs, from CLI programs to websites. * The tools surrounding python are much more mature, widely used, and accessible (Jupyter, Pycharm, Anaconda). * Cross-language support is far far better for python. (Running C++ code through python for example). * Cross-platform support is far far better for python. Matlab is kept alive by aggressively selling to universities, whose students go on to use it afterwards. Thankfully this is changing, and many universities now teach python in STEM courses like physics and maths.
@gourabghosh5574
@gourabghosh5574 4 жыл бұрын
Please make more videos on manim
@moonlightcocktail
@moonlightcocktail 4 жыл бұрын
Is there a left-truncatable prime as well?
@skylardeslypere9909
@skylardeslypere9909 4 жыл бұрын
Yes, 4260 en.m.wikipedia.org/wiki/Truncatable_prime
@alexpotts6520
@alexpotts6520 4 жыл бұрын
There are, but they are both much more numerous and can grow far larger than the right-truncatable ones because there's none of the (1, 3, 7, 9) restriction going on. This means that at each step, you have more options to extend the number, so it can continue for significantly longer before you run out of primes. I don't know whether it would be feasible to do the same thing for LT primes. The program would be very similar, but the computation would be far, far longer.
@giuseppemalaguti435
@giuseppemalaguti435 4 жыл бұрын
Scusa la mia ignoranza, ma che software usi?
@spaghettiking653
@spaghettiking653 4 жыл бұрын
Python IDLE :)
@sovietcat919
@sovietcat919 4 жыл бұрын
papa I am back I am sorry that I am late
@lordofcastamere9376
@lordofcastamere9376 4 жыл бұрын
Papa this python not C. We use Python because we're lazy
@mudkip_btw
@mudkip_btw 4 жыл бұрын
Kinda nice :p
@holyshit922
@holyshit922 4 жыл бұрын
He has learned programming in Python ?
@geniusgamer8046
@geniusgamer8046 3 жыл бұрын
12th
@guill3978
@guill3978 4 жыл бұрын
How do you proove that that number is prime?
@aldobernaltvbernal8745
@aldobernaltvbernal8745 4 жыл бұрын
count it's factors
@PopeLando
@PopeLando 4 жыл бұрын
Every composite (non-prime) number is either a square number or the product of two numbers, one of which must be smaller than the square root. So for numbers of reasonable size (as here, 8 digits) for each number you are testing just check all the numbers less than its square root to see if the remainder from dividing is zero. If no such numbers are found (every remainder > 0), then the number is prime. For 8 digit numbers the square root has a maximum of 4 digits, so it's reasonably quick. For much bigger numbers you use clever primality tests which work by raising some number to a power of the testee, using modular arithmetic to make it easier to handle the giant powers.
@Evan-ne5bu
@Evan-ne5bu 4 жыл бұрын
Man this is incredible to me, considering the fact that I don't even know how to write a program in html or any other programming language
@akshat9282
@akshat9282 4 жыл бұрын
mans considering html as programming language, where's reddit at
@akshat9282
@akshat9282 4 жыл бұрын
jokes aside, learning to code is easier than you'd think and absolutely wonderful. you'll find amazing tutorials on KZbin itself. try it, I'm sure you'd love it
@Evan-ne5bu
@Evan-ne5bu 4 жыл бұрын
@@akshat9282 the point is that I've never been presented a pure mathematical way of using coding and programming, so I've never been interested in programming
@ChongFrisbee
@ChongFrisbee 4 жыл бұрын
@@Evan-ne5bu I present you Haskell. Next step is to realize you don't need a reason not to be interested in code. You do you
@whitealpha2265
@whitealpha2265 4 жыл бұрын
Ayyy I'm early af papa
@guill3978
@guill3978 4 жыл бұрын
Find 100-digit primes.
@skylardeslypere9909
@skylardeslypere9909 4 жыл бұрын
It'd just be: import math primelist = [ ] a = 10^100 # smallest 100-digit number b = 10^101 - 1 # largest 100-digit number for i in range(a, b): for j in range(1, math.floor(math.sqrt(i)): if i%j == 0: break else: primelist.append(i) print(primelist)
@skylardeslypere9909
@skylardeslypere9909 4 жыл бұрын
I believe this should work. Not 100% sure about the prime-checking bit
@guill3978
@guill3978 4 жыл бұрын
@@skylardeslypere9909 The program wouldn't be able to check that it's not divisible by each prime less than its square root, which is 10 to the 50. Doing obout 10^48 trial divions for that porpuse seems completely unfeasible.
@Periiapsis
@Periiapsis 4 жыл бұрын
You could use a prime sieve but it would take really long. Best you could do is generate random odd numbers until you find one passes a primality test like the Miller-Rabin primality test Edit: actually you could loop through every 100 digit number and use the Miller-Rabin primality on each number. You can also optimize it such as only looking at numbers that are either 1 or 5 mod 6
@skylardeslypere9909
@skylardeslypere9909 4 жыл бұрын
@Guille it would be able too, it'd just take really long. But I included a loop from 1 to sqrt(i) where i goes from every number between 10^100 and 10^101 - 1 That would be 9.10^100 iterations for the first loop. Take that to the ~10^50 power a'd that would be the total amount of iterations. In other words: ( 9×10^100)^(10^50) It'd probably never finish even with a quantum computer but it'd work in theory
@Spongman
@Spongman 4 жыл бұрын
yuck, free yourself from the loops and mutables. this, like most problems can simply be solved using functional style. here's a c# example, but this can also be done easily in python: repl.it/repls/LimegreenThisDeskscan
6. Laplace Transform of f(t) = cosh(at)
2:03
MathandBolt
Рет қаралды 65
POV: Your kids ask to play the claw machine
00:20
Hungry FAM
Рет қаралды 18 МЛН
My daughter is creative when it comes to eating food #funny #comedy #cute #baby#smart girl
00:17
TREE vs Graham's Number - Numberphile
23:50
Numberphile
Рет қаралды 1,2 МЛН
PyMath #1 - When Dividorial and π Meet - Their Beautiful Relationship
19:34
73939133 - Probably the Most Interesting Prime Number [Part 1]
16:57
Flammable Maths
Рет қаралды 39 М.
906,150,257 and the Pólya conjecture (MegaFavNumbers)
12:11
SparksMaths
Рет қаралды 58 М.
The Reciprocals of Primes - Numberphile
15:31
Numberphile
Рет қаралды 1,6 МЛН
What is the biggest tangent of a prime?
10:59
Stand-up Maths
Рет қаралды 359 М.
The number behind an impossible building: 1,056,006
11:36
Eddie Woo
Рет қаралды 34 М.
The BEST Way to Find a Random Point in a Circle | #SoME1 #3b1b
18:35