Golang 程式查詢整數的最小子除數
假定整數為:75
該整數的除數是:3、5、15,...,75
最小的除數為:3
步驟
- 從使用者處獲取一個整數。
- 使用該數字初始化一個變數 (res)。
- 使用一個 for 迴圈,其中 i 的值介於 2 到該整數之間。
- 如果該數字可以被 i 整除,則將其與 res 比較。如果 res > i,則使用 i 更新 res。
- 退出迴圈並列印 res。
示例
package main
import "fmt"
func main(){
var n int
fmt.Print("Enter the number: ")
fmt.Scanf("%d", &n)
res := n
for i:=2; i<=n; i++{
if n%i == 0{
if i<=res{
res=i
}
}
}
fmt.Printf("The smallest divisor of the number is: %d", res)
}輸出
Enter the number: 75 The smallest divisor of the number is: 3
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP