Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

Напишите программу Python, которая считает количество простых чисел в заданной…

  1. User

    Напишите программу Python, которая считает количество простых чисел в заданной последовательности и выводит ответ на экран. Простое число делится только на себя и на единицу. Последовательность задаётся при помощи вызова ввода (input) на каждой итерации цикла. Одна итерация — одно число.

  2. Assistant

    Программа будет запрашивать числа у пользователя до тех пор, пока не будет введено отрицательное число или ноль. Для определения является ли число простым, будет использоваться функция is_prime(). После ввода каждого числа, программа будет проверять его на простоту, и если число является простым, счетчик простых чисел будет увеличиваться на 1. В конце программа выведет количество простых чисел на экран.

    def is_prime(num):
        if num < 2:
            return False
        for i in range(2, int(num**0.5) + 1):
            if num % i == 0:
                return False
        return True
    
    count = 0
    
    while True:
        number = int(input("Введите число: "))
        if number <= 0:
            break
        if is_prime(number):
            count += 1
    
    print("Количество простых чисел:", count)
    

    Пример работы программы:

    Введите число: 3
    Введите число: 7
    Введите число: 13
    Введите число: 21
    Введите число: 0
    Количество простых чисел: 3
    
  3. User

    Solve this on Haskell

  4. Assistant

    Sure! Here's the equivalent solution in Haskell:

    isPrime :: Int -> Bool
    isPrime num
        | num < 2 = False
        | otherwise = all (\x -> num `mod` x /= 0) [2..(floor $ sqrt $ fromIntegral num)]
    
    countPrimes :: [Int] -> Int
    countPrimes = length . filter isPrime
    
    main :: IO ()
    main = do
        putStrLn "Enter a sequence of numbers:"
        numbers <- getContents
        let numList = map read $ words numbers :: [Int]
        let primeCount = countPrimes numList
        putStrLn $ "Number of prime numbers: " ++ show primeCount
    

    This program defines two helper functions: isPrime to check if a number is prime, and countPrimes to count the number of prime numbers in a list. In the main function, the program prompts the user for a sequence of numbers, reads them from standard input, and passes them to countPrimes to determine the count of prime numbers. Finally, it prints the result to the console.

  5. User

    Solve this on Haskell

  6. Assistant

    Certainly! Here's a Haskell program that counts the number of prime numbers in a given sequence:

    isPrime :: Int -> Bool
    isPrime n = n > 1 && all (\x -> n `mod` x /= 0) [2..(floor $ sqrt $ fromIntegral n)]
    
    countPrimes :: [Int] -> Int
    countPrimes = length . filter isPrime
    
    main :: IO ()
    main = do
      putStrLn "Enter numbers (separated by spaces):"
      input <- getLine
      let numbers = map read $ words input :: [Int]
      let primeCount = countPrimes numbers
      putStrLn $ "Number of prime numbers: " ++ show primeCount
    

    The program defines isPrime to check if a number is prime. It checks if the number is greater than 1 and then iterates over all numbers from 2 to the square root of the number, checking if the number is divisible evenly by any of them. If no divisor is found, the number is prime.

    The countPrimes function takes a list of numbers and filters it to only include the prime numbers. It then returns the length of the filtered list.

    In the main function, the program prompts the user to enter a sequence of numbers, reads the input, converts it to a list of integers, and passes that list to countPrimes to get the count of prime numbers. Finally, it prints the result to the console.

  7. User

    Solve this on Haskell

  8. Assistant

    Certainly! Here's a Haskell program that counts the number of prime numbers in a given sequence:

    isPrime :: Int -> Bool
    isPrime n
        | n <= 1 = False
        | otherwise = all (\x -> n `mod` x /= 0) [2..floor(sqrt(fromIntegral n))]
    
    countPrimes :: [Int] -> Int
    countPrimes = length . filter isPrime
    
    main :: IO ()
    main = do
        putStrLn "Enter a sequence of numbers (space-separated):"
        input <- getLine
        let numbers = map read $ words input :: [Int]
        let primeCount = countPrimes numbers
        putStrLn $ "Number of prime numbers: " ++ show primeCount
    

    The program defines isPrime to check if a number is prime. It first checks if the number is less than or equal to 1, in which case it returns False. Otherwise, it uses all function to check if the number is not divisible evenly by any number from 2 to the square root of the number.

    The countPrimes function takes a list of numbers and filters it to only include the prime numbers. It then returns the length of the filtered list.

    In the main function, the program prompts the user to enter a sequence of numbers, reads the input, converts it to a list of integers, and passes that list to countPrimes to get the count of prime numbers. Finally, it prints the result to the console.

  9. User

    isPrime in Haskell

  10. Assistant

    Certainly! Here's an implementation of the isPrime function in Haskell:

    isPrime :: Int -> Bool
    isPrime n
      | n <= 1 = False
      | otherwise = not $ any ((== 0) . (n `mod`)) [2..(floor (sqrt (fromIntegral n)))]
    

    This isPrime function takes an integer n as input and returns a boolean value indicating whether n is prime or not.

    • If n is less than or equal to 1, it is not prime, so the function returns False.
    • Otherwise, it uses any function with a check to see if there exists any number between 2 and the square root of n (inclusive) that divides n evenly (i.e., has a remainder of 0 when n is divided by it). The any function returns True if any element satisfies this condition. However, we negate the result using not to indicate primality.

    By doing so, the isPrime function effectively checks if a number is divisible by any number from 2 to the square root of that number. If it is divisible by any of those numbers, it is not prime. Otherwise, it is prime.