Python and Prime Numbers || Python Tutorial || Learn Python Programming

Socratica · 219K views · 2017 · 6:02

Open on YouTube

Python, Ruby & scripting languagesAlgorithms & data structuresSoftware performance & optimizationtutorial

Why Stack Overflow recommends it

Stack Overflow users link it when answering prime-checking questions, either as a beginner-friendly walkthrough or as the source for the optimized is_prime approach.

Recommended by 1 people across 1 different months, 2018 to 2020.

What it is

A short Socratica tutorial that writes a Python function to test whether a number is prime, then profiles it and walks through several ways to make it faster. It is presented by Ulka Simone Mohanty and ties the topic to cryptography and number theory.

What people said

Strong rec amunnelly · 2020-01 · Stack Overflow · on “Prime number list code not working. How to fix it?”

Socratica do really excellent, user-friendly, newbie-friendly tutorials on YouTube. Check out this on on generating lists of primes in Python: [this video]

Cites Zilong Li · 2018-09 · Stack Overflow · on “I made a prime number checker in python. Can it be optimized?”

This one might be faster: import math def is_prime(n): ''' return True if n is a prime number. False otherwise.''' # negative numbers, 0, and 1 are not prime if n <= 1: return False # 2 is prime if n == 2: return True # non-2 even numbers are not prime if n % 2 == 0: return False # loop through odd divisors up to its sqrt for i in range(3, math.ceil(math.sqrt(n)), 2): if n % i == 0: return False return True Reference (Socratica): [this video]

Cites Rafael Lima · 2019-10 · Stack Overflow · on “Can't define 2 as prime number or not”

I'm trying to define prime numbers, but my algorithm doesn't recognize 2 as a prime number . Instead return None . I try it in Google Colab , Jupiter Notebook and PyCharm with same result. My code: # V1) Test all divisors from 2 through n-1. (skip 1 and n) def is_prime_v1(n): """ Return 'True' if 'n' is a prime number. False otherwise. """ if n == 1: return False # 1 is not prime for d in range(2, n): if n % d == 0: return False # Is not prime return True # ===== Test Function ===== for n in range(1, 21): print(n, is_prime_v1(n)) My output: 1 False 2 None 3 True 4 False 5 True 6 False 7 True 8 False 9 True 10 False 11 True 12 False 13 True 14 False 15 True 16 False 17 True 18 False 19 True 2