Ok, so as you know I am following MIT 6.00 Introduction to Computer Science and Programming course, so for first class assignment was to write a program that returns all the first X primes. Or the X prime (if you prefer that).
It took me 1.51 hours to freaking get it right. Damn… my mind is way far from where it should be. Main point though:
- I have clearly not interiorized enough how exactly “while” loops work, and when the program stops or “exits” the loop and all.
- I need to then revise and analyze the program that I myself wrote over and over again, to make sure I understand the logic behind it, and I can explain it.
Below is the code I wrote, which works pretty well if you input what is intended, although I have not tested errors and strange inputs.
The key really is to understand the indentations (so important in python), and when you exit one indentation and go back to previous. That is something I will review next time.
Now, just as an exercise I want to define in words what the program is doing and my thoughts on it:
Basically the key to understand this section is to understand that the while loop is going to perform a function until some condition is met. In order for the loop to finish, you need to make sure that at some point in the loop, the condition will be met.
An easy way to start is to define a loop that does 100 lops. This is easy, you just set a variable = o, and tell the loop to run until that variable is 100. Then in the loop there should be a command that increases the value of the variable on each loop so that eventually you reach the 100 and the loop stops.
In the program I wrote below there are 2 loops. One basically tells the program to continue calculating numbers until we find a determined amount of primes (basically everytime we find a prime the counter goes up).
Then there is another loop that says keep dividing the current number by a divisor, until this divisor reaches a certain value. This divisor has an initial state , and in each subsequent loop it changes. Then it is interesting because on the third branch, basically we define that whenever a number if divided by another gives remainder 0, then this is not a prime so the loop should end. The way to make the loop end is to make sure that the divisor is set to a condition at the end of branch , that will force the loop to stop!
current_number = 2 prime_counter = 1 x = input ("How many primes do you want me to produce?") prime_wanted = x while (prime_counter < prime_wanted): if current_number % 2.0 != 0: divisor = current_number - 1 while (divisor >= 1): if divisor == 2: print "you have hit a prime " + str(current_number) + " is the " + str(prime_counter) + " prime" prime_counter = prime_counter + 1 divisor = divisor - 1 elif current_number % divisor != 0: divisor = divisor - 1 else: divisor = 0 current_number = current_number + 1 raw_input ("program has finished")