Question d’entretien chez Apple

given an integer, write code to list all primes preceding it.

Réponses aux questions d'entretien

Utilisateur anonyme

2 août 2014

This solution can be optimized further. No need to check for even numbers (except 2, 2 is the only prime even number). You can find if 'n' is prime when it is not divisible by any number between 2 to n/2. More optimizaton can be achieved if the range is reduced further from 2 to sqrt(n). But finding a sqrt will be tedious and might require inclusion of math.h library.

3

Utilisateur anonyme

29 sept. 2014

there is a much more optimal solution, think about what you already know ;-) of course if this was an interview this would be my answer too (unless they asked for more performance.)

1

Utilisateur anonyme

21 juin 2015

void printPrimes (int N) { int i; int * isNotP = malloc(sizeof(int) * N); if (isNotP == NULL) return; if (N < 2) { printf("Error in input %d\n", N); return; } if (N == 2) { printf("- 2 -\n"); return ; } memset(isNotP, 0, sizeof(int) * N); for (i = 3; i <= N; i+=2) { int k = i*i; isNotP[i-1] = 1; while (k <= N) { isNotP[k] = 1; k += i; } } printf("- 2 -\n"); for (i = 3; i <= N; i+=2) if (isNotP[i] == 0) printf("- %d -\n", i); }

Utilisateur anonyme

21 nov. 2018

#!usr/bin/python def PrintPrecedingPrimes(x): for i in range(1, x): if i == 1 or i <= 0: pass elif i == 2: print(2) else: if all(i%j != 0 for j in range(2,int(i/2) + 1)): print(i) else: pass try: inp = int(input("Enter Value:")) PrintPrecedingPrimes(inp) except Exception as e: print(e)

Utilisateur anonyme

16 oct. 2019

var primes = [Int]() for i in 2...100 { print (i, terminator: ": ") var primeCount = 0 findPrimes: for prime in primes { if prime > i / 2 { break findPrimes } if i % prime == 0 { primeCount += 1 print (prime, terminator: " ") } } if primeCount == 0 { primes.append(i) } print() } print("[", terminator:" ") for prime in primes { print(prime, terminator: " ") } print()

Utilisateur anonyme

30 juil. 2014

void printPrime(int n) { bool not_prime = false; for (int i=2; i

1