简体   繁体   中英

Write a program to print first x terms of the series 3N + 2 which are not multiples of 4

n = int (input())
for x in range (1, n + 1, 1):
    for y in range (1, 100, 1):
        z = 3 * y + 2
        if z % 4 != 0:
            print(z, end=' ')

This code can print the number which are not the multiples of 4, but how to make to stop after printing first 'n' numbers (z) which are not multiples of 4?

Input: 10

Expected output: 5 11 14 17 23 26 29 35 38 41

Actual Output: 5 11 14 17 23 26 29 35 38 41 47 50 53 59 62 65 71 74 77 83 86 89 95 98 101 107 110 113 119 122 125 131 134 137 143 146 149 155 158 161 167 170 173 179 182 185 191 194 197 203 206 209 215 218 221 227 230 233 239 242 245 251 254 257 263 266 269 275 278 281 287 290 293 299

Keep it simple and efficient with a generator.

Use itertools.islice and itertools.count :

from itertools import islice, count

N = 10
l = list(islice((x for i in count(start=1) if (x:=3*i+2)%4), N))

output: [5, 11, 14, 17, 23, 26, 29, 35, 38, 41]

Introduce a counter-variable:

n = int (input())
counter = 0
for x in range (1, n + 1, 1):
    for y in range (1, 100, 1):
        z = 3 * y + 2
        if counter >= 10:
            break
        if z % 4 != 0:
            print(z, end=' ')
            counter += 1
limit = 10
counter = 0
n = 0

while counter != limit:
    n += 1
    statement = (3*n)+2
    if (statement % 4 != 0) and (statement > 4):
        print(statement)
    counter += 1
n= int(input())
count=0
x=1
while(count<n):
    y=3*x+2
    if(y%4!=0):
        print(y, end=' ')
        count=count+1
    x=x+1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM