0

I have an input called divisibleBy which is an integer. I want to get all the possible numbers that it is divisible with except itself.

For example:

var divisibleBy = 16;

the output should be "2,4,8". "16" was not included because it is equal to itself. Now i want it to be a list but without using for loop. It could be using a LINQ or whats your recommended. since there is a possibility that the divisbleBy can be greater than 1000 so looping would cause performance issue.

heres my current code using loop

var list = new List<int>();
for (var cols = divisibleBy - 1; cols > 0; cols--)
{
    if (divisibleBy % cols != 0) continue;

    list.Add(cols);
}
Rashid
  • 1,700
  • 1
  • 23
  • 56
  • Did you try anything? – Rafalon Oct 05 '18 at 07:32
  • @Rafalon yes I try but using loops. cannot formulate yet any LINQ equivalent – Rashid Oct 05 '18 at 07:32
  • You do know that using Linq doesn't mean it doesn't use hidden loops, right? – Rafalon Oct 05 '18 at 07:33
  • i know but it is more faster right? I update the code to show how I do it. – Rashid Oct 05 '18 at 07:34
  • 1
    *"can be greater than 1000 so looping would cause performance issue."* Nope. Your CPU performs billions of operations per seconds. Do the math. :-) – Heinzi Oct 05 '18 at 07:34
  • 2
    *"i know but [LINQ] is more faster right?"* Nope, it's just more convenient to read and write. – Heinzi Oct 05 '18 at 07:34
  • @Heinzi what happens if this was an api and there are thousands of users also? – Rashid Oct 05 '18 at 07:36
  • I have closed your question as a duplicate, because the linked question already contains a lot of implementations, including some done with LINQ. If you think that this is in error, please clarify and I will reopen your question. – Heinzi Oct 05 '18 at 07:36
  • `Enumerable.Range(1, aim-1).Where(a => aim%a == 0).ToList();` - but that'll still loop through your range – Rafalon Oct 05 '18 at 07:38
  • @Heinzi so for this it is much better to use loops right? – Rashid Oct 05 '18 at 07:38
  • @SecretCoder: Then it might make sense to cache the result for commonly occurring numbers. And of course there is potential for optimization in your loop (for example, it suffices to check until sqrt(divisibleBy)), but you can't avoid a certain minimum time complexity. – Heinzi Oct 05 '18 at 07:38
  • @SecretCoder: For your use case, any possible implementation (explicit loop, LINQ, ...) is probably fine. If you are unsure, benchmark your code. – Heinzi Oct 05 '18 at 07:39
  • @Heinzi thanks, got the point now. – Rashid Oct 05 '18 at 07:40
  • `var result = Enumerable.Range(2, value - 3).Where(item => value % item == 0).ToList();` – Dmitry Bychenko Oct 05 '18 at 07:58

0 Answers0