给定一个整数判断是否为素数_Ruby程序检查给定数字是否为素数
給定一個整數(shù)判斷是否為素數(shù)
檢查素數(shù) (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.
在編寫代碼之前,讓我們了解素數(shù)到底是什么? 這樣我們就可以輕松設計其邏輯并在代碼中實現(xiàn)它。 質(zhì)數(shù)是那些只能被自身或1整除的數(shù)。因此,我們將設計一個可以滿足質(zhì)數(shù)性質(zhì)的代碼。
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 :用于將字符串轉(zhuǎn)換為整數(shù)。
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.
+ :通常在代碼中用于增加循環(huán)變量。
Variables used:
使用的變量:
num: It is storing the user inputted integer value.
num :存儲用戶輸入的整數(shù)值。
count: Initialised with 0 and used as a counter variable.
count :以0初始化,并用作計數(shù)器變量。
Ruby代碼檢查天氣是否為素數(shù) (Ruby code to check weather a number is prime or not)
=begin Ruby program to check whether the given number is prime or not. =endputs "Enter the number:" num=gets.chomp.to_i count=0 if (num==0)puts "0 is not prime" elsei=2while(i<num)if (num%i==0)count+=1endi+=1endendif count>1puts "#{num} is not a prime number"elseputs "#{num} is a prime number"endOutput
輸出量
RUN 1 : Enter the number: 13 13 is a prime numberRUN 2: Enter the number: 890 890 is not a prime numberCode 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.
該程序檢查整數(shù)輸入是否為素數(shù) 。 使用while循環(huán)和條件檢查輸入。 根據(jù)條件檢查,代碼將打印所需的輸出。
翻譯自: https://www.includehelp.com/ruby/check-whether-the-given-number-is-prime-or-not.aspx
給定一個整數(shù)判斷是否為素數(shù)
總結(jié)
以上是生活随笔為你收集整理的给定一个整数判断是否为素数_Ruby程序检查给定数字是否为素数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 编辑距离 dp_使用动态编程(DP)编辑
- 下一篇: 原生js设置div隐藏或者显示_Java