Advertisement
brownbear

MIT OCW Intro to Computer Science Problem Set 1

May 7th, 2011
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. prime_candidate=3
  2. prime_counter=0
  3. #we are neglecting 2, so only go up to 999
  4. while prime_counter<999:
  5. prime_divisor=2
  6. ##prime_divisor is here so that it gets reset at the beginning of each round in the while loop
  7. while prime_divisor<(prime_candidate/2)
  8. if prime_counter%prime_divisor>0:
  9. ###checking to see if there is a remainder
  10. prime_divisor=prime_divisor+1
  11. prime_counter=prime_counter+1
  12. print prime_candidate
  13. prime_candidate=prime_candidate+2
  14. ##setting prime_candidate as the next odd number
  15. print prime_candidate 'is the 1000th prime'
  16.  
  17. EDITED: V2.0
  18.  
  19. prime_candidate=3
  20. #prime_candidate variable is the number being checked if prime
  21. prime_counter=0
  22. #prime_counter is keeping track of which prime number we are on
  23. #we are neglecting 2, so only go up to 999
  24. while prime_counter<999:
  25. prime_divisor=2
  26. ##prime_divisor is here(after the first while) so that it gets reset at the beginning of each round in the while loop
  27. while prime_divisor<(prime_candidate/2):
  28. ###since we are using integer division, it is ok to divide prime_candidate by 2, as the remainder will be thrown away
  29. if prime_counter%prime_divisor>0:
  30. ###checking to see if there is a remainder
  31. prime_divisor=prime_divisor+1
  32. if prime_counter%prime_divisor==0:
  33. ###if there is no remainder, it isn't prime, moving on to the next odd number
  34. prime_candidate=prime_candidate+2
  35. prime_counter=prime_counter+1
  36. print prime_candidate
  37. prime_candidate=prime_candidate+2
  38. ##setting prime_candidate as the next odd number
  39. print prime_candidate + 'is the 1000th prime'
  40.  
  41. V3.(1):
  42.  
  43. prime_number_candidate=1
  44. prime_counter=0
  45. while prime_counter<999:
  46. prime_number_candidate=prime_number_candidate+2
  47. primecheck=True
  48. prime_divisor=2
  49. ##initialized here so that they are reset at each round of the loop
  50. while prime_divisor<(prime_number_candidate/2):
  51. ###while loop to determine if the number is still prime after being divided by every number less than n/2
  52. if prime_number_candidate%prime_divisor>0:
  53. #### % operator to determine if there is a remainder
  54. prime_divisor=prime_divisor+1
  55. else:
  56. primecheck=False
  57. prime_divisor=prime_number_candidate+1
  58. prime_number_candidate=prime_number_candidate+2
  59. if primecheck==True:
  60. prime_counter=prime_counter+1
  61. print prime_number_candidate
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement