Hello coders, in this post we are going to learn how to find factors of a number using Go Programming language.
A Factor is a number that divides the given number without any remainder. For example: 3 is a factor of 72 because 72 is exactly divisible by 3 leaving no remainder.
We will be using the same logic to find factors of a number.
So, without further ado, let's begin the tutorial.
Table Of Contents 👊
Go Program To Find Factors of a Number
// Go Program To Find Factors of a Number
package main
import "fmt"
func main(){
var num, i int
// Asking for Input
fmt.Print("Enter an number:")
fmt.Scan(&num)
fmt.Println("Factors of", num, "are:")
// logic
for i = 1; i <= num; i++{
if (num % i == 0){
fmt.Println(i)
}
}
}
Output
Enter an number:112
Factors of 112 are:
1
2
4
7
8
14
16
28
56
112
How Does This Program Work ?
var num, i int
In this program, we have declared two int data type variables named as i and num.
fmt.Print("Enter an number:")
fmt.Scan(&num)
Then, the user is asked to enter an number. The value of this integer is stored in num variable.
for i = 1; i <= num; i++{
if (num % i == 0){
fmt.Println(i)
}
}
This program starts from 1 and iterated until i is equal to n. The program check whether num is exactly divisible by i or not. If the condition becomes true, then i is one of the factors of num. Then, we print the factorial number.
Conclusion
I hope after reading this post, you understand how to find factors of a number using Go Programming language.
If you have any doubts regarding the problem, feel free to contact in the comment section.