给定一个整数判断是否为素数
检查素数 (Checking prime number)
Before getting into writing the code, let us understand what exactly the prime numbers are? So that we could easily design its logic and implement it in the code. Prime numbers are those numbers which can only be divisible by itself or 1. So, we will design a code which can fulfill the property of prime numbers.
在编写代码之前,让我们了解素数到底是什么? 这样我们就可以轻松设计其逻辑并在代码中实现它。 质数是那些只能被自身或1整除的数。因此,我们将设计一个可以满足质数性质的代码。
Methods used:
使用的方法:
puts: For giving the output as well as a message to the user.
puts :用于向用户提供输出和消息。
gets: For taking the input from the user.
gets :用于接受用户的输入。
.to_i: For converting strings into integers.
.to_i :用于将字符串转换为整数。
Operators used:
使用的运算符:
%: For retrieving the remainder.
% :用于检索剩余部分。
==: Used for comparing two values.
== :用于比较两个值。
< and >: These are comparison operators.
<和> :这些是比较运算符。
+: Generally used in the code for incrementing the loop variable.
+ :通常在代码中用于增加循环变量。
Variables used:
使用的变量:
num: It is storing the user inputted integer value.
num :存储用户输入的整数值。
count: Initialised with 0 and used as a counter variable.
count :以0初始化,并用作计数器变量。
Ruby代码检查天气是否为素数 (Ruby code to check weather a number is prime or not)
=begin
Ruby program to check whether the given number is
prime or not.
=end
puts "Enter the number:"
num=gets.chomp.to_i
count=0
if (num==0)
puts "0 is not prime"
else
i=2
while(i<num)
if (num%i==0)
count+=1
end
i+=1
end
end
if count>1
puts "#{num} is not a prime number"
else
puts "#{num} is a prime number"
end
Output
输出量
RUN 1 :
Enter the number:
13
13 is a prime number
RUN 2:
Enter the number:
890
890 is not a prime number
Code explanation:
代码说明:
This program checks whether the integer input is prime or not. The input is checked using the while loop and conditions. Based on the condition check the code prints the required output.
该程序检查整数输入是否为素数 。 使用while循环和条件检查输入。 根据条件检查,代码将打印所需的输出。
翻译自: https://www.includehelp.com/ruby/check-whether-the-given-number-is-prime-or-not.aspx
给定一个整数判断是否为素数