Loops Posted Aug 26, 2020

Let's assume we are given a number n. we need to print all the numbers till the given number n, such that for every number if there exists a prime factor, we need to print those prime factors instead of that number in the set. For example, if we are given the number as 10. we need to print the output as: 1 2 3 2 5 2 3 7 2 3 2 5

Let's understand the expected output.

```
1
2
3
2 <- for 4, since 4 = 2 x 2
5
2 3 <- for 6, since 6 = 2 x 3
7
2 <- for 8, since 8 = 2 x 4
3 <- for 9, since 9 = 3 x 3
2 5 <- for 10, since 10 = 2 x 5
```

**How do we solve this?**

Let's try to approach it like this:

- Maintain a list of primes we have encountered through out the loop, say
**primes**. - For every element in the series till the limit
**n**, say**x** - maintain a flag
**isPrime**to check if there was a factor or not, set to true - Loop from 2 till the number
**x**, with a counter**i** - Check if there is any
**i**that is a factor of**x** - if there is this
**i**in the**primes**, print the number**i** - unset the flag
**isPrime**, since we know that**i**is a factor of**x** - End of the loop
- if the counter
**i**is equal to**x**and**isPrime**is still set to true, add the current number**x**to the set of**primes**we're maintaining. - The same process is repeated for all the numbers till the limit
**n**

*Code in C#:*

```
public class PrimeFactorBuzz
{
HashSet<int> primes = new HashSet<int>();
public void DoPrimeFactors(int n)
{
for (int i = 1; i <= n; i++)
{
PrimeFactor(i);
}
}
public void PrimeFactor(int number)
{
bool isPrime = true;
int up = number;
int i = 2;
while (i < up)
{
if (number % i == 0)
{
if (primes.Contains(i))
Console.Write($"{i} ");
isPrime = false;
}
i++;
}
if (number == 1)
Console.Write($"{number} ");
if (i == up && isPrime)
{
Console.Write($"{number} ");
primes.Add(number);
}
}
}
```

Enjoy this article?
*Buy Me a Coffee*

Join the community! Like on Facebook Follow on Twitter

Compute and generate a compressed string for a given string containing repetitions

Find all possible natural numbers below a given limit such that a3+b3 = c3+d3

Find all the pairs in a given ordered set of numbers whose sum is equal to a given input sum

Find all the pairs in a given unordered set of numbers whose sum is equal to a given input sum

Sort the given unordered set of Binary digits

(UPDATED to .NET 6) Implementing CQRS with MediatR in ASP.NET Core

(UPDATED to .NET 6) Calling Stored Procedures in ASP.NET Core / EF Core

(UPDATED to .NET 5) Integrating OData with ASP.NET Core Web API

Integrating MongoDB with ASP.NET Core (.NET 6)

Implementing Role based and Claims based Authorization in ASP.NET Core (.NET 5)