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
极客教程