Day 25: Running Time and Complexity

Sort by

recency

|

812 Discussions

|

  • + 0 comments

    include

    include

    const char* is_prime(int n) { if (n <= 1) { return "Not prime"; } if (n <= 3) { return "Prime"; } if (n % 2 == 0 || n % 3 == 0) { return "Not prime"; }

    // Check for divisibility from 5 to sqrt(n)
    for (int i = 5; i * i <= n; i += 6) {
        if (n % i == 0 || n % (i + 2) == 0) {
            return "Not prime";
        }
    }
    return "Prime";
    

    }

    int main() { int n; printf("Enter a number: "); scanf("%d", &n);

    printf("%s\n", is_prime(n));
    

        return 0; }

  • + 0 comments

    t=int(input()) for _ in range(t): n=int(input()) if n<=1: print('Not prime') else: for i in range(2,int(n**0.5)+1): if(n%i)==0: print('Not prime') break else: print('Prime')

  • + 0 comments

    javaScript Solution

    function processData(input) { const numbers = input.split('\n').slice(1).map(Number);

    numbers.forEach(number => { console.log(isPrime(number) ? 'Prime' : 'Not prime'); }); }

    function isPrime(num) { if (num <= 1) return false; if (num <= 3) return true; if (num % 2 === 0 || num % 3 === 0) return false;

    for (let i = 5; i * i <= num; i += 6) { if (num % i === 0 || num % (i + 2) === 0) return false; }

    return true; } `

  • + 0 comments
    C# Csharp
    
        static void Main(String[] args) 
        {
            int row = int.TryParse(Console.ReadLine(), out int inputRow) ? inputRow : 0;
    
            while (row > 0)
            {
                int.TryParse(Console.ReadLine(), out int rec);
    
                if (rec > 1)
                {
                    bool isPrime = true;
    
                    // Optimized primality test: check divisors only up to the square root
                    for (int i = 2; i * i <= rec; i++)
                    {
                        if (rec % i == 0)
                        {
                            isPrime = false;
                            break;
                        }
                    }
    
                    string result = isPrime ? "Prime" : "Not prime";
                    Console.WriteLine(result);
                }
                else
                {
                    Console.WriteLine("Not prime");
                }
    
                row--;
            }
        }
    
  • + 0 comments
    def isprime(p):
        if p <= 1:
            return 'Not prime'
        if p <= 3:
            return 'Prime'
        if p % 2 == 0 or p % 3 == 0:
            return 'Not prime'
        i = 5
        while i * i <= p:
            if p % i == 0 or p % (i + 2) == 0:
                return 'Not prime'
            i += 6
        return 'Prime'
    
    x = int(input())
    for _ in range(x):
        p = int(input())
        print(isprime(p))