john bowers, professor mike lam, professor · 2018. 3. 20. · cs 280 spring 2018 john bowers,...

Post on 22-Aug-2020

1 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

CS 280Spring 2018John Bowers, ProfessorMike Lam, Professor

Complete Search

Complete Search

l Aka “brute force”

l Simply try every possibility

l Won’t work for every problem!

l Feasible only for small domains

Complete Search

l Example 1: Selection sort

l For each position find the max value (from remainder of list)

l Example 2: Naïve GCD (greatest common divisor)

l Try all k from min(m,n) to 1

l Check whether k divides m and n, if so we’ve found GCD

l Example 3: Primality test

l Try all k from 2 to sqrt(n)

l Check whether k divides n, if so n is not prime

Complete Search

l General tips:

l Prune the search space if possible (don’t waste timechecking impossible candidates)

l Utilize symmetries

l Pre-compute whatever you can

l Try working backwards

l Use a better data structure

Solved Problem

Solutions

PYTHON:

import math

N = int(input())sqrtN = int(math.floor(math.sqrt(N)) + 1)

nums = set()for i in range(1, sqrtN):

if N % i == 0:nums.add(i - 1)nums.add(N / i - 1)

print (' '.join([str(int(s)) for s in sorted(nums)]))

In-class problem

top related