#求100以内所有素数之和并输出。 #素数指从大于1,且仅能被1和自己整除的整数。# method1
count=0for i inrange(2,101):# when i is 2 ,means in the next line will generate range(2,2) , it's illegal in math for i1 inrange(2,i):# as for range(2,2) , this For cycle is ineffective if i%i1==0:break#so the break is ineffective neither else:#that why the "else" for 2 is useful
count+=i
print(count)
test code
count=0for i inrange(2,4):print("*")for i1 inrange(2,i):print("&")if i%i1==0:breakelse:
count+=i
print(count)for i inrange(2,2):print(i)print("^")print("?")
test code result
* //2
* //3
& //just 3
5
?
*************************routinely*****************************# method2
count=2# treat 2 as the first prime number for i inrange(3,101):# the edge is between 3 and 101for i1 inrange(2,i):#(2 ~ i-1)if i%i1==0:breakelse:
count+=i
print(count)
result
M1 : 1060
M2 : 1060
another example
from time import perf_counter
c=""#i=1234
start=perf_counter()for i inrange(1000,10000):
c=str(i)
new=0for b inrange(4):
new=new+pow(eval(c[b]),4)if new==i:print(i)print("time with method 1 is : {}\n".format(perf_counter()-start))
t=""
start1=perf_counter()for i inrange(1000,10000):
t =str(i)ifpow(eval(t[0]),4)+pow(eval(t[1]),4)+pow(eval(t[2]),4)+pow(eval(t[3]),4)== i :print(i)print("time with method 2 is :{}\n".format(perf_counter()-start1))
i=6688
c="6688"
new=0for b inrange(4):
new=new+pow(eval(c[b]),4)print("new:",new)if new==i:print(i)print("the right answer\n")
i=6688
c="6688"
new=0for b inrange(4):
new=new+pow(eval(c[b]),4)print("new:",new)if new==i:print(i)print("wrong example : the layer of the for cycle is wrong so it outputs 6688")print("because it compares ever temporary variable of 'new' to the 'i' but not to wait for the correct result of 'new' ")
result
1634
8208
9474
time with method 1 is : 1.1122524802377804
1634
8208
9474
time with method 2 is :1.0024570370526817
new: 1296
new: 2592
new: 6688
new: 10784
the right answer
new: 1296
new: 2592
new: 6688
6688
new: 10784
wrong example : the layer of the for cycle is wrong so it outputs 6688
because it compares ever temporary variable of 'new' to the 'i' but not to wait for the correct result of 'new'
something interesting with ‘For cycle’ in pythonkey point : for_cycle & break & else#求100以内所有素数之和并输出。 ...