Newby Coder header banner

Algorithm

What is an algorithm

An algorithm is a formula or set of steps for solving a particular problem or doing a particular work

Typically, an algorithm has a stopping point and provides a solution

There can be multiple algorithms for a problem, where some are slower than others

Algorithms can be expressed in any language, from natural languages like English to programming languages like Java

It is basically logic written in pseudo-code by software developers to illustrate the steps required to reach a result

A computer program can be viewed as an algorithm or combination of algorithms

Example

A simple algorithm can be that of finding the prime numbers from 2 to a given number

Following is a simple algorithm, which can be stated in a high-level description in English as:

Following is a sample pseudo code for above algorithm

Algorithm PrimeNumbers
  Input: A number n
  Output: list of prime numbers upto n

  if n <2 return null
  primes = [2]
  for each number from 3 to n do:
    divisible = false
    for each prime in primes do:
        if number % prime == 0:
            divisible = true
            break
    if not divisible:
        primes.add(number)
  return primes

Flow chart of Euclid's algorithm to find the greatest common divisor of two numbers (source:wikipedia)