python algorithm for prime numbers -
assume availability of function is_prime . assume variable n has been associated positive integer. write statements needed find out how many prime numbers (starting 2 , going in increasing order successively higher primes [2,3,5,7,11,13,...]) can added before exceeding n . associate number variable k .
def main(): n=int(input('n: ')) k=0 i=2 sum=0 while sum<=n: if is_prime(i): sum+=i i+=1 k+=1 print(k) def is_prime(n): divisor in range(2,int(n**0.5)+1): if n/divisor==int(n/divisor): return false return true main()
would appreciate pointers.
i modified code little bit , working fine program grades these codes says should using + sign where. have no idea. modified code is:
while sum<=n: if is_prime(i): sum+=i k+=1 i+=1 print(k)
output:
n: 10
i: 2
2
i: 3
5
when should go upto i=5 , total =10.
if n/divisor==int(n/divisor):
this wrong. when divide 2 integers integer result. 5/2 = 2. replace with
if n%divisor == 0:
edited: modified loop looks correct. if understand task right should be
while sum<=n: if is_prime(i): sum+=i k+=1 i+=1 print(k)
edited2: want stop sum + next prime bigger n , not add prime value.
while true: if is_prime(i): if(sum + > n) break; else: sum += k += 1 += 1 print(k)
Comments
Post a Comment