8TILMATE
8TILMATE

Reputation: 17

find the exact numbers that have 3 divisors and are smaller than n(given by the user)

I am a 9th grader that just learned some basic algorithms in pseudocode and tried solving a problem in python. The ex. required me to find the numbers that have 3 divisors and are smaller than n. what should I do? there is no output

[1]: https://i.sstatic.net/a69tA.png**strong text**

n=int(input("introduce a  nr"))
x=1
k=0
d=1
for x in range(1,n+1):
    for d in range(1,x+1):
        if x % d==0:
            k+=1
        d+=1
    if k==3:
      print(x)
    x+=1

Upvotes: 0

Views: 192

Answers (2)

Jeromba6
Jeromba6

Reputation: 433

Some extra when you want to know by which numbers it can be divided:``

#!/bin/env python3

n = int(input("introduce a  nr: "))
for x in range(1, n+1):
    diverders = []
    for d in range(1, x+1):
        if x % d == 0:
            diverders.append(d)

    if len(diverders) == 3:
        print(f'{x} can be devided by {diverders}')

Upvotes: 0

John Coleman
John Coleman

Reputation: 52008

The main problem is that you are not reinitializing k beofre for each invocation of the inner loop. Another problem is that you are not trusting for loops to do what they are designed to do. Things like d += 1 are pointless.

The following code works:

n=int(input("introduce a  nr: "))

for x in range(1,n+1):
    k = 0
    for d in range(1,x+1):
        if x % d==0:
            k+=1
    if k==3:
      print(x)

The output (for n = 1000) is:

4, 9, 25, 49, 121, 169, 289, 361, 529, 841, 961

Interestingly, this is sequence A001248 in the On-line encyclopedia of integer sequences. That sequence is describes as being the sequence of all squares of primes. It is easy to see that this another way of describing the sequence that you are trying to find.

Upvotes: 1

Related Questions