Skip to content
This repository has been archived by the owner on Jun 8, 2023. It is now read-only.

Use Fermat's Little Theorem to check if a number if prime. #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

paterson
Copy link

@paterson paterson commented May 6, 2014

Hey there :)

Using Fermat's Little Theorem is a much much more efficient way of checking if a number is prime than the way you were doing it. This should make prime checking, and prime generation a lot faster.

Fermat's Little Theorem is as follows:

equation

In Ruby thats:

a ** p % p == a

I ran numerous benchmarks on my machine (MacBook Pro):

https://gist.github.com/paterson/18493006a7c673e8beaa

(Results are in gist).

Anyway I was studying and got kinda bored. Should help, it's not always that one line pull request can make an up to 90000% speed improvement :)

Using Fermat's Little Theorem is a much more efficient way of checking if a number is prime (200-300% for ~500 numbers generation. Significant increase at ~10000). This should make prime checking, and prime generation a lot faster.
@paterson paterson changed the title Update one_liner.rb Use Fermat's Little Theorem to check if a number if prime. May 6, 2014
@paterson paterson changed the title Use Fermat's Little Theorem to check if a number if prime. Use Fermat's Little Theorem to check if a number if prime. This increases performance by up to 90,000% May 6, 2014
@paterson paterson changed the title Use Fermat's Little Theorem to check if a number if prime. This increases performance by up to 90,000% Use Fermat's Little Theorem to check if a number if prime. May 6, 2014
@paterson
Copy link
Author

paterson commented May 6, 2014

WIP. Don't merge yet. Thanks!

@jihyeseo
Copy link

An intriguing thought!
Any prime number p satisfies the equation, but there are p which are not prime, but still satisfies the same equation.
https://en.m.wikipedia.org/wiki/Carmichael_number

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants