Olimpiadi Italiane di Informatica – Correttore online – Facili
Sia x un numero intero.
Diremo che y è un divisore di x se 1 <= y <= x e il resto della divisione di x per y è uguale a zero.
Si chiede di contare tutti i possibili divisori di un dato numero x.
Esempi di input/output
+-----------+------------+
| input.txt | output.txt |
+----+-----------+------------+
| 1° | 12 | 6 |
+----+-----------+------------+
| 2° | 239 | 2 |
+----+-----------+------------+
1
Come dice il testo, y è un divisore di x se
1 <= y <= x
- il resto della divisione per x di y è uguale a zero:
(x%y == 0)
x = int(input("x = "))
conta = 0
for y in range(1, x+1):
if(x%y == 0):
conta += 1
print(conta)
2
Se aggiungi una funzione print() all’interno dell’if() visualizzerà tutti i divisori
...
print(y, end=" ")
...
3
Realizza una funzione
def f(x):
conta=0
for y in range(1, x+1):
if(x%y == 0):
conta += 1
return conta
numero=f(10) # 4
OII
Versione con file come richiesto dalle OII
def f(x):
conta=0
for y in range(1, x+1):
if(x%y == 0):
conta += 1
return conta
f=open("input.txt", "r")
stringa=f.read()
f.close()
x=int(stringa)
numero=f(x)
f=open("output.txt", "w")
f.write(str(numero))
f.close()
4
Quanti divisori hanno i numeri minori di 100?
def f(x):
conta=0
for y in range(1,x+1):
if(x%y == 0):
conta += 1
return conta
N=range(1,100)
NUM=99*[0]
for n in N:
quanti=f(n)
NUM[n-1]=quanti
print(NUM)
matplotlib

import matplotlib.pyplot as plt
def f(x):
conta=0
for y in range(1,x+1):
if(x%y == 0):
conta += 1
return conta
N=range(1,100)
NUM=99*[0]
for n in N:
quanti=f(n)
NUM[n-1]=quanti
plt.bar(N,NUM)
plt.label("Conteggi dei divisori")
plt.ylabel(Numero")
plt.show()