How to write a program in Ruby which finds first 10 prime numbers?
- User
How to write a program in Ruby which finds first 10 prime numbers?
Assistant
ruby# Define a method to check if a number is prime def is_prime?(number) # Iterate from 2 to the square root of the number (2..Math.sqrt(number)).each do |divisor| # If the number is divisible by any number from 2 to its square root, it is not prime return false if number % divisor == 0 end # If the number is divisible by no number from 2 to its square root, it is prime true end # Initialize the count of prime numbers found prime_count = 0 # Iterate starting from 2 until 10 prime numbers are found number = 2 while prime_count < 10 # Check if the current number is prime if is_prime?(number) # Increment the count of prime numbers found prime_count += 1 # Print the prime number puts number end # Increment the number to check number += 1 end
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.