Harukomaze
Harukomaze

Reputation: 462

problems with a for-loop in C#

I am very new to C# programming (2 days in so far), after learning intermediate python and doing a few small projects, I am trying to learn C#

But because me knowing python, I am finding C# a little confusing, arrays always throw me off, while in python initializing a list is as easy as declaring a variable with empty lists x = [], C#'s way of declaring arrays is confusing.

My issue is, I encountered an error, which I did google but found nothing (there was one question similar to mine but no one had answered on it)

I was on a site called https://codewars.com/ and was solving Katas (problems) [lvl 7 (beginner)]

The question stated that for any input integer n, I have to return an array with a factor of the number n where n > 1

In python, the code will be like this:

def findFactors(n):
    return [x for x in range(2, n) if n % x == 0]

So I converted the code to the best of my abilities this:

public class Kata
{
  public static int[] Divisors(int n)
  {
  int counter = 0;
  int[] myNum = {};
  for (int i=2; i == n; i++) {
    int calculate = n % i;
    if (calculate==0) {
      myNum.CopyTo(i, counter);
      counter++;
    }  
  }
    if (myNum.Length == 0) {
      return null;
    }
    else {
      return myNum;
    }
  }
}

The error I got was:

src/Solution.cs(10,20): error CS1503: Argument 1: cannot convert from 'int' to 'System.Array'

Compared to error tracebacks in python, C# Tracebacks are a little harder to comprehend

So how can I fix this error?

Upvotes: 0

Views: 127

Answers (1)

Enigmativity
Enigmativity

Reputation: 117019

To fix your code you'd need to do this:

public static int[] Divisors(int n)
{
    int[] myNum = { };
    for (int i = 2; i < n; i++)
    {
        int calculate = n % i;
        if (calculate == 0)
        {
            int[] x = new int[myNum.Length + 1];
            myNum.CopyTo(x, 0);
            x[x.Length - 1] = i;
            myNum = x;
        }
    }
    return myNum;
}

But the direct equivalent to your original code is this:

public static int[] Divisors(int n)
    => Enumerable.Range(2, n - 2).Where(x => n % x == 0).ToArray();

Or using an iterator:

public static IEnumerable<int> Divisors(int n)
{
    for (int i = 2; i < n; i++)
    {
        if (n % i == 0)
        {
            yield return i;
        }
    }
}

Upvotes: 2

Related Questions