CS61A disc01

Write a function that returns True if a positive integer n is a prime number and False otherwise. Hint: use the % operator: x % y returns the remainder of x when divided by y.

A prime number: if it has two factors: 1 and the number itself

1-- no 2-- yes 3--yes 4--no 7-- yes

A prime number should not have any factors other than these two. -- when you go from 2 to n-1, should not find any non-trival factors that divides n without a remainder. 

you can loop through all numbers from 2 to n-1 using the range() object in python. 

range(start, stop, step) returns a range object. you can iterate over the range object to get a sequence from start to stop-1, in step of step.

so 2 to n-1 : for i in range(2, n)

1, if you find a number that divides n evenly without a remainder, you can conclude that the number is not prime. 

2, if you've looped through the entire range of numbers from 2 to n-1 without finding a nuber that divides n evenly, then the number is prime. 

def is_prime(n):

      for i in range(2, n):

           if n % i == 0; 

               return False

       return True

Optimize

4-1,2,4  5-1,5 6-1,2,3,6 9-1,3,9 10-1,2,5,10 18-1,2,3,6,9,18

the only factor of n that is greater than n/2 is n itself

we can instead run the loop only up to n/2

def is_prime(n):

      for i in range(2, int(n/2)):

           if n % i == 0:

                  return False

       return True

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值