elz (
elz) wrote in
intro_to_cs2009-11-11 05:21 pm
![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
![[community profile]](https://www.dreamwidth.org/img/silk/identity/community.png)
Entry tags:
Lecture 2
Problem set 1: Computing prime numbers, product of primes
This one's a little trickier, so feel free to comment if you run into any problems or want to brainstorm with other people!
(eta: having issues with poll, alas)
no subject
no subject
I'm a lot like you, I think. This is my first non-HTML code because I self-taught in HTML by taking other people's source code and manipulating it to see how they'd done what they did. Hang in there a little longer and see if it clicks? If not, I don't mean to push you or frustrate you more.
no subject
I'm grateful to have a community working on this stuff--thanks to all of you who have commented.
no subject
yvixSJkxBtcbHfBLqiT
(Anonymous) 2012-01-09 04:22 am (UTC)(link)no subject
If it helps, here's how I'd translate the pseudocode I just gave you into real python:
n = the number we're checking
(raw_input prompts the user and returns their answer; we need to typecast the input from a string to a number using int, or otherwise the computer will think it's text and whine at us)
start with x = 2, 'cause it's the smallest prime
(nothing really fancy there)
while x < n
(another place where the python bears a striking resemblance to the pseudocode)
if n is divisible by x
(use the modulus function to see if x divides evenly into n)
n is not prime, we can stop checking now
(breaks you out of the while loop, and sets your "instruction counter" at the instruction immediately after it)
otherwise,
*
n might still be prime!
(since our program is assuming n is prime until told otherwise, already, there's no need to translate this into code)
set x to the next value to check divisibility with
(sets x to old-x + 1)**
and run through the loop again
(you don't actually need to put anything here for this, in python. When the interpreter reaches the end of a while loop, it will automatically go back to the top, assuming the loop condition (x < n) still holds true)
*You don't actually need to use an else case for this, because there's a break statement in the if case, but it's a more direct translation of the pseudocode.
**It would be faster to only check n's divisibility with just primes, rather than with all integers, but that is beyond the scope of this simple example. ^^
no subject
no subject
LjdywZEBondMs
(Anonymous) 2011-08-14 05:08 am (UTC)(link)