Last active
October 11, 2019 12:32
-
-
Save ajarmst/73ae04184b1addd13058ae7e9b762cac to your computer and use it in GitHub Desktop.
Demo Code for Iteration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
print("Loop Demos") | |
# i = 5 | |
# while i < 5: | |
# print (str(i) + "!") | |
# i+=1 #(i = i+1) | |
# print("All done.") | |
# i = 5 | |
# while i < 5: | |
# print (str(i) + "!") | |
# i+=1 #(i = i+1) | |
# if (i <4 ): | |
# break | |
# else: | |
# print("All done.") | |
# for c in "AJ Armstrong": | |
# print(c) | |
# for x in range(10,0,-1): | |
# print(x) | |
# for x in range(1,int(1e6),10): | |
# if x%51 == 0: | |
# break | |
# elif x%31 == 0: | |
# continue | |
# print (str(x) + ", ", end='') | |
#Prime Number Search | |
#Prints primes in range 2 to argument | |
def primes(x): | |
DEBUG=True #Use to change output style | |
if x < 2 : | |
print("There are no prime numbers less than 2.") | |
for p in range(2,x): | |
if DEBUG:print("Prime Candidate:" + str(p)) | |
prime=True # Assume prime, then start looking for factors | |
#Free number theory lecture: If there are no factors | |
#of p less than or equal to the square root of p (math.sqrt(p)) | |
#then p is prime. | |
for f in range(2,int(math.ceil(math.sqrt(p)))): | |
#Did I find a factor on a previous loop iteration? | |
if not prime: | |
break | |
if DEBUG:print(" Checking possible factor: " + str(f)) | |
#is f a factor of p? | |
if(p%f==0): #if no remainder for f/p, f is a factor of p | |
if DEBUG:print(" " + str(p) + " is not prime.") | |
prime=False | |
#no point in carrying on, we know this isn't prime | |
continue | |
if prime: | |
if DEBUG: | |
print("*** " + str(p) + " is prime. ***" ) | |
else: | |
print(str(p) + " ", end="") | |
print() # Make sure a blank line at the end of output. | |
primes(100) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment