7
CS 280 Spring 2018 John Bowers, Professor Mike Lam, Professor Complete Search

John Bowers, Professor Mike Lam, Professor · 2018. 3. 20. · CS 280 Spring 2018 John Bowers, Professor Mike Lam, Professor Complete Search

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: John Bowers, Professor Mike Lam, Professor · 2018. 3. 20. · CS 280 Spring 2018 John Bowers, Professor Mike Lam, Professor Complete Search

CS 280Spring 2018John Bowers, ProfessorMike Lam, Professor

Complete Search

Page 2: John Bowers, Professor Mike Lam, Professor · 2018. 3. 20. · CS 280 Spring 2018 John Bowers, Professor Mike 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

Page 3: John Bowers, Professor Mike Lam, Professor · 2018. 3. 20. · CS 280 Spring 2018 John Bowers, Professor Mike Lam, Professor Complete Search

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

Page 4: John Bowers, Professor Mike Lam, Professor · 2018. 3. 20. · CS 280 Spring 2018 John Bowers, Professor Mike Lam, Professor Complete Search

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

Page 5: John Bowers, Professor Mike Lam, Professor · 2018. 3. 20. · CS 280 Spring 2018 John Bowers, Professor Mike Lam, Professor Complete Search

Solved Problem

Page 6: John Bowers, Professor Mike Lam, Professor · 2018. 3. 20. · CS 280 Spring 2018 John Bowers, Professor Mike Lam, Professor Complete Search

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)]))

Page 7: John Bowers, Professor Mike Lam, Professor · 2018. 3. 20. · CS 280 Spring 2018 John Bowers, Professor Mike Lam, Professor Complete Search

In-class problem