Home > Software design >  Write a program to print first x terms of the series 3N 2 which are not multiples of 4
Write a program to print first x terms of the series 3N 2 which are not multiples of 4

Time:03-04

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

CodePudding user response:

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]

CodePudding user response:

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

CodePudding user response:

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
  • Related