0

I am designing a program that asks for the user to input 2 numbers. It then finds the prime factors of each number. The number of prime factors depends on what number the user inputs. I need an array whose number of elements isn't known ahead of time so that I can input the prime factors of one of the numbers into the array of variable length.

int a = -1, b = -1;
string sa, sb;
int GCF = 0;
int LCM = 0;
int temp = 1, tempb = 1; 
int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 
                       47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};

while (aValid == true)
{
for (int i = 0; i < 25; i++)
{
if (a % primes[i] == 0)
{
Console.Write(" ");
Console.Write(primes[i]);
//my attempt below to input current prime factor into variable array
int[] arrb = primes[i];
a = a / primes[i];
}
}
if (a == 1)
{
break;
}
}
  • 4
    `List` is an array whose number of elements isn't known ahead of time – Sergey Berezovskiy May 24 '20 at 18:42
  • 3
    Use a List instead of an array? Array lengths are fixed and cannot be changed. See https://programmingwithmosh.com/net/csharp-collections/ or one of the other numerous tutorials and resources online; search for “C# collections”. – user2864740 May 24 '20 at 18:42
  • This answered in stackoverflow [here](https://stackoverflow.com/questions/599369/array-of-an-unknown-length-in-c-sharp) – Peter Marshall May 24 '20 at 18:55

1 Answers1

0

You can use List<int> instead of int array. When declaring a new List you don't need to specify the capacity. In your code, add the following line above while loop:

List<int> arrb = new List<int>();

Then replace int[] arrb = primes[i]; with

arrb.Add(primes[i]);
mb14
  • 460
  • 4
  • 14