Напишите программу Python, которая считает количество простых чисел в заданной…
- User
Напишите программу Python, которая считает количество простых чисел в заданной последовательности и выводит ответ на экран. Простое число делится только на себя и на единицу. Последовательность задаётся при помощи вызова ввода (input) на каждой итерации цикла. Одна итерация — одно число.
- 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 - User
Solve this on Haskell
- 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 primeCountThis program defines two helper functions:
isPrimeto check if a number is prime, andcountPrimesto count the number of prime numbers in a list. In themainfunction, the program prompts the user for a sequence of numbers, reads them from standard input, and passes them tocountPrimesto determine the count of prime numbers. Finally, it prints the result to the console. - User
Solve this on Haskell
- 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 primeCountThe program defines
isPrimeto 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
countPrimesfunction 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
mainfunction, 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 tocountPrimesto get the count of prime numbers. Finally, it prints the result to the console. - User
Solve this on Haskell
- 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 primeCountThe program defines
isPrimeto check if a number is prime. It first checks if the number is less than or equal to 1, in which case it returnsFalse. Otherwise, it usesallfunction to check if the number is not divisible evenly by any number from 2 to the square root of the number.The
countPrimesfunction 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
mainfunction, 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 tocountPrimesto get the count of prime numbers. Finally, it prints the result to the console. - User
isPrime in Haskell
- Assistant
Certainly! Here's an implementation of the
isPrimefunction in Haskell:isPrime :: Int -> Bool isPrime n | n <= 1 = False | otherwise = not $ any ((== 0) . (n `mod`)) [2..(floor (sqrt (fromIntegral n)))]This
isPrimefunction takes an integernas input and returns a boolean value indicating whethernis prime or not.- If
nis less than or equal to 1, it is not prime, so the function returnsFalse. - Otherwise, it uses
anyfunction with a check to see if there exists any number between 2 and the square root ofn(inclusive) that dividesnevenly (i.e., has a remainder of 0 whennis divided by it). Theanyfunction returnsTrueif any element satisfies this condition. However, we negate the result usingnotto indicate primality.
By doing so, the
isPrimefunction 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. - If