Tutte le sfide
Facile 7 risolte 38.9% di accettazione

Prime Number Check

Decide whether a number is prime.

Cosa imparerai

  • Test divisibility with the % operator
  • Stop checking at the square root of n
  • Handle 0, 1 and 2 as special cases

Problema

Mostra traduzione

A prime number is greater than 1 and divisible only by 1 and itself. Checking divisors up to the square root of n is enough.

Implement is_prime(n).

Input

n: The number to test.

Output

Return true if n is prime, otherwise false.

Vincoli

-1,000 ≤ n ≤ 1,000,000,000,000

Esempi

Esempio 1
Input:
n = 29

Output atteso:
expected = True
Input:
long long n = 29;

Output atteso:
bool expected = true;
Input:
long n = 29;

Output atteso:
bool expected = true;

Spiegazione

29 has no divisors other than 1 and 29.

Esempio 2
Input:
n = 21

Output atteso:
expected = False
Input:
long long n = 21;

Output atteso:
bool expected = false;
Input:
long n = 21;

Output atteso:
bool expected = false;

Spiegazione

21 = 3 × 7, so it is not prime.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Handle numbers below 2 first; they cannot be prime.

Suggerimento 2

Test possible divisors only up to the square root of the number.

Suggerimento 3

Watch out for even numbers and repeated factors, since one divisor is enough to disqualify primality.

Complessità attesa

O(sqrt(n)) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 ННикита Python 1,059 ms - 5/5 Vedi il codice
2 AAmir Python 1,098 ms - - Vedi il codice
3 KKKaneki Ken Python 1,137 ms - 5/5 Vedi il codice
4 JPJittipat Phonhan Go 1,547 ms - 5/5 Vedi il codice
5 GTGarlic The Destroyer Rust 1,759 ms - 2/5 Vedi il codice
6 HJhettory Jurash C++ 4,287 ms - 4/5 Vedi il codice
7 PTphúc thịnh phạm C++ 4,447 ms - 4/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 7 soluzioni complete sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le recensioni AI. Accedi e risolvi la sfida per partecipare alla discussione.