日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

给定一个整数判断是否为素数_Ruby程序检查给定数字是否为素数

發布時間:2025/3/11 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 给定一个整数判断是否为素数_Ruby程序检查给定数字是否为素数 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

給定一個整數判斷是否為素數

檢查素數 (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. =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"end

Output

輸出量

RUN 1 : Enter the number: 13 13 is a prime numberRUN 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

給定一個整數判斷是否為素數

總結

以上是生活随笔為你收集整理的给定一个整数判断是否为素数_Ruby程序检查给定数字是否为素数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。