logoNEURAL COOK
SearchAll PostsTagsNotesAuthor
logoNEURAL COOK

A posts created with Next.js and Tailwind.css

Explore

  • All posts
  • Notes
  • Snippets
  • Tags
  • RSS feed

Connect

instagramtwitterfacebookyoutubelinkedinmailgithub

© 2026 VIKI. All rights reserved.

Built with
Contents
ArraysBoyer-Moore Majority Vote AlgorithmKadane’s AlgorithmTriple Reverse algorithm aka Reversal Algorithm
Cycle detectionDijkstraDisjoint Set UnionGraphTopological SortTraversal algorithmsTree Traversal
Binary HeapBinomial HeapHeap
Cycle DetectionLinked ListSorting
Finding the majority elementRotate array by K steps
Finding If Number is PrimeGCD of two numbersPerforming ExponentiationPrime NumbersRandomising Data
3. Max Consecutive OnesHoare'S Partition SchemeLomuto Partition Scheme
DequesPriority QueueQueue
The Binary Search Master GuideThe Rotated Sorted Array Master Guide
Bubble SortCounting SortInsertion SortMerge SortPigeon Hole SortQuick SortSelection Sort
Monotonic StackMonotonic StackStackReversing an ArrayStackTower of Hanoi
Binary Tree TraversalCentre of gravityDiameter of TreeShortest Path
Algorithmic Pattern/numerical algorithms

Prime Numbers

4 min read
On this pageFinding Prime Factors
Finding Prime FactorsFinding Primes <a href="#head-3-11" id="head-3-11"></a>Testing for Primality

A prime number (or simply prime) is a counting number (an integer greater than 0) greater than 1 whose only factors are 1 and itself.

# Finding Prime Factors

An obvious way to find a number's prime factors is to try dividing the number by all of the numbers between 2 and 1 less than the number. When a possible factor divides the number evenly, save the factor, divide the number by it, and continue trying more possible factors.

List&lt;Integer&gt; findFactors(int num) {
    List&lt;Integer&gt; factors = new ArrayList<>();
    
    // check for 2
    if(num%2 == 0) {
        factors.add(2);
        while(num%2 == 0) num/= 2;
    }
    
    int upperBound = Maths.sqrt(num);
    
    // only check for odd numbers
    for (int i = 3; i &lt; upperBound; ) {
        if(num%i == 0){
            factors.add(i);
            while(num%i == 0) num/=i;
            upperBound = Maths.sqrt(num);
        }
        i+=2;
    }
    
    // If there's anything left of the number, it is a factor, too.
    if(num &gt; 1) factors.add(num)
    return factors;
}

Try the same factor again before moving on in case the number contains more than one copy of the factor.

Some optimisation

  • don't need to test whether the number is divisible by any even number other than 2 because, if it is divisible by any even number, it is also divisible by 2.
  • only need to check for factors up to the square root of the number.
    • if n=p∗qn=p*qn=p∗q , then either ppp or qqqmust be less than or equal to n\sqrt{n}n​. (If both are greater than n\sqrt{n}n​ , then their product is greater than nnn.
  • Every time dividing the number by a factor, update the upper bound on the possible factors that need to be checked.

This prime factoring algorithm has run time O(n)\text{O}(\sqrt{n})O(n​)

Info

The method of trying all the possible factors smaller than a number is called trial division. There are other factoring methods, such as wheel factorization and various field sieves.

# Finding Primes

The sieve of Eratosthenes is a simple method to find all of the primes up to a given limit.

Idea is to make a table with one entry for each of the numbers between 2 and the upper limit.

  • Cross out all of the multiples of 2 (not counting 2 itself).
  • Then, starting at 2, look through the table to find the next number that is not crossed out (3 in this case).
  • Cross out all multiples of that value (not counting the value itself).
    • Note that some of the values may already be crossed out because they were also a multiple of 2.
  • Repeat this step, finding the next value that is not crossed out and crossing out its multiples until you reach the square root of the upper limit.
  • At the end any numbers that are not crossed out are prime.

This algorithm has run time O(n∗log⁡(log⁡n))\text{O}(n*\log{(\log{n}))}O(n∗log(logn)) , but that is beyond the scope of this book.

It requires a table with entries for every number that is considered. Therefore uses an unreasonable amount of memory if the numbers are too large.

# Testing for Primality

A way to determine whether a number is prime is to use finding prime factors algorithm to try to factor it and if the algorithm doesn't find any factors, then the number is prime.

Fermat's “little theorem” states that if ppp is prime and 1≤n≤p1 \le n \le p1≤n≤p, then np−1%p=1n^{p-1}\%p = 1np−1%p=1

  • it is possible for np−1%p=1n^{p-1}\%p = 1np−1%p=1 , even if ppp is not prime in such case, the value nnn is called a Fermat liar because it incorrectly implies that ppp is prime.
  • If np−1%p=1n^{p-1}\%p = 1np−1%p=1, then n is called a Fermat witness because it proves that ppp is not prime.

for a natural number , at least half of the numbers between 1 and ppp are Fermat witnesses. On repeating the test many times, can increase the chances to pick a witness if one exists.

  • there is a 50% chance to pick a Fermat wintess.
  • So, if ppp passes kkk tests, there is a chance of picking Fermat liars every time. In other words, there is a 12k\frac{1}{2^{k}}2k1​ chance that it is actually a composite number pretending to be prime.

Info

This is an example of a probabilistic algorithm—one that produces a correct result with a certain probability.

←PreviousPerforming ExponentiationNext→Randomising Data

On this page

Finding Prime FactorsFinding Primes <a href="#head-3-11" id="head-3-11"></a>Testing for Primality