Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to display factors of entered number
A factor of a number is any integer that divides the number evenly without leaving a remainder. For example, the factors of 12 are 1, 2, 3, 4, 6, and 12 because each of these numbers divides 12 exactly.
To find factors of a number in C#, we use the modulus operator (%) to check if the remainder is zero when dividing the number by potential factors.
Algorithm
The algorithm to find factors involves the following steps −
Start with 1 and iterate through all numbers up to the given number
For each number, check if it divides the given number evenly using the modulus operator
If the remainder is 0, then it's a factor
Syntax
The basic syntax for finding factors using a loop −
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
Console.WriteLine(i);
}
}
Example
Here's a complete program to find and display all factors of a given number −
using System;
class Program {
static void Main(string[] args) {
int number = 12;
int i;
Console.WriteLine("Finding factors of: " + number);
Console.WriteLine("Factors:");
for (i = 1; i <= number; i++) {
if (number % i == 0) {
Console.WriteLine(i);
}
}
}
}
The output of the above code is −
Finding factors of: 12 Factors: 1 2 3 4 6 12
Optimized Approach
For better performance with large numbers, we can optimize by checking factors only up to the square root of the number −
using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args) {
int number = 36;
List<int> factors = new List<int>();
Console.WriteLine("Finding factors of: " + number);
for (int i = 1; i * i <= number; i++) {
if (number % i == 0) {
factors.Add(i);
if (i != number / i) {
factors.Add(number / i);
}
}
}
factors.Sort();
Console.WriteLine("Factors:");
foreach (int factor in factors) {
Console.WriteLine(factor);
}
}
}
The output of the above code is −
Finding factors of: 36 Factors: 1 2 3 4 6 9 12 18 36
Using a Method
We can create a reusable method to find factors of any number −
using System;
class Program {
static void FindFactors(int number) {
Console.WriteLine("Factors of " + number + ":");
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
Console.Write(i + " ");
}
}
Console.WriteLine();
}
static void Main(string[] args) {
FindFactors(20);
FindFactors(15);
FindFactors(7);
}
}
The output of the above code is −
Factors of 20: 1 2 4 5 10 20 Factors of 15: 1 3 5 15 Factors of 7: 1 7
Conclusion
Finding factors of a number in C# involves using the modulus operator to check divisibility. The basic approach iterates from 1 to the number, while the optimized approach only checks up to the square root for better performance with large numbers.
