Step 1 If n = 0, return m and stop; otherwise go to Step 2 Step 2 Divide m by n and assign the value of the remainder to r Step 3 Assign the value of n to m and the value of r to n. Go to Step 1.
Remember, the same algorithm may be represented in several different ways …
Step 4 Compute the product of all the common prime factors and return it as gcd (m,n )
Prime Factorisation Input: Integer x ≥ 2, Output: List F of prime factors of x P ← Sieve(x) while n > 1 do while n mod P[i] = 0 do F ← F + P[i] x ← x / P[i] i ← i + 1 Sieve of Eratosthenes Input: Integer x ≥ 2 Output: List of primes less than or equal to x for p ← 2 to x do A [ p ] ← p for p ← 2 to x do if A [ p ] 0 j ← p * p while j ≤ x do A [ j ] ← 0 j ← j + p
How does the performance of this algorithm compare to Euclid’s and Consecutive Integer Checking?
Note also that an algorithm will be required to find all common prime factors too…
We usually evaluate sorting algorithm complexity by the number of key comparisons .
Two important properties
Stability : A sorting algorithm is called stable if it preserves the relative order of any two equal elements in its input.
In place : A sorting algorithm is in place if it does not require extra memory, except, possibly for a few memory units.
27.
Sorting Problems SelectionSort(A[0..n-1]) //Input: An array A[0..n-1] of orderable elements //Output: Array A[0..n-1] sorted in ascending order for i ← 0 to n – 2 do min ← i for j ← i + 1 to n – 1 do if A[j] < A[min] min ← j swap A[i] and A[min]
An example of a simple (and often low-performance) sorting algorithm is Selection Sort
Binary Search // Input: sorted array a_i < … < a_j and key x; m (i+j)/2; while i < j and x != a_m do if x < a_m then j m-1 else i m+1; if x = a_m then output a_m;
Given a set of items, each with a weight and a value, determine the most valuable subset of items with total weight less than or equal to a given limit
A sequence of n items of the same data type that are stored contiguously in computer memory and made accessible by specifying a value of the array’s index.
Array properties
fixed length (need preliminary reservation of memory)
A sequence of zero or more nodes each containing two kinds of information: some data and one or more links called pointers to other nodes of the linked list.
An ordered tree is a rooted tree in which all the children of each vertex are ordered.
Binary trees
A binary tree is an ordered tree in which every vertex has no more than two children and each children is designated s either a left child or a right child of its parent.
Be the first to comment