給定一個整數判斷是否為素數
檢查素數 (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
給定一個整數判斷是否為素數