-1

I am new to C#. I am trying to bring numbers from a txt file into my program and multiply them. The text file would be formatted like this:

1
2
3
4
5
6
7
8
9
10

I need the program to do 1x2x3x4x5x6x7x8x9x10=3628800.

This is a list of 2 million different numbers.

I can get it to output to a text file, just not input. I have looked around and can't really see an answer.

Thanks.

Himanshu
  • 4,327
  • 16
  • 31
  • 39

4 Answers4

0

You can do this with few lines of code.

var lines = File.ReadLines(fileName);
var collection = new List<int>();

foreach (var line in lines)
{
   collection.AddRange(line.Split(' ').Select(n => Convert.ToInt32(n)));  
}

var result = collection.Distinct().Aggregate((i, j) => i * j); // remove distinct if you don't want eliminate duplicates.
Hari Prasad
  • 16,716
  • 4
  • 21
  • 35
0

You can try this

string value1 = File.ReadAllText("file.txt");
int res = 1;
var numbers = value1.Split(' ').Select(Int32.Parse).ToList();
for(int i=0;i<numbers.Count;i++)
{
    res = res * numbers[i];
}
Console.WriteLine(res);
Mohit S
  • 13,723
  • 6
  • 34
  • 69
0
var numbers = File.ReadAllText("filename.txt").Split(' ').Select(int.Parse); // Read file, split values and parse to integer
var result = numbers.Aggregate(1, (x, y) => x * y); // Perform multiplication
imlokesh
  • 2,506
  • 2
  • 22
  • 26
0

You want to multiply 2 million numbers all together, but there is a problem.

The problem is memory limitation. to hold a big number you have to use BigInteger class inside System.Numerics namespace.

You can use this reference by adding Using keyword in top of your project.

using System.Numerics;

If the compiler did not recognize Numerics then You need to add an assembly reference to System.Numerics.dll.

Your code should look like this.

string inputFilename = @"C:\intput.txt"; // put the full input file path and name here.

var lines = File.ReadAllLines(inputFilename); // put text lines into array of string.

BigInteger big = new BigInteger(1); // create the bigInt with value 1.

foreach (var line in lines) // iterate through lines
{
    big *= Convert.ToInt32(line); // Multiply bigInt with each line.
}

string outputFilename = @"C:\output.txt"; // put the full output file path and name here

File.WriteAllText(outputFilename, big.ToString()); // write the result into text file

This may take a long time to complete. but this all depends on hardware that is operating. You may get memory overflow exception during this task which depends on amount of memory you have.

Community
  • 1
  • 1
M.kazem Akhgary
  • 18,645
  • 8
  • 57
  • 118
  • This is working so far, The only answer that I can get to even work without throwing an exception. Thank you for the nice explanations too. – John Fitch Sep 14 '15 at 05:38