I was solving CodeWars task(https://www.codewars.com/kata/5e4bb05b698ef0001e3344bc/train/csharp) and faced a problem. In it you are given the array of numbers, which length is multiply of 4, you need to visualise it as a (x1^2 x2^2) * (x3^2 x4^2) .... * (xn^2 xn 1^2). Calculate the result of this and find 2 numbers, which squares in sum, gives the result of initial sequance. For example, you are given an array of ( 2, 1, 3, 4): (2^2 1^2) * (3^2 4^2) = 125; 2 numbers, which squares in sum will give 125, is 2 and 11 because 4 121 = 125; I wrote the code and it works with most of examples, but when i use big arrays such as (3, 9, 8, 4, 6, 8, 7, 8, 4, 8, 5, 6, 6, 4, 4, 5) in result i receive (0,0); I can't get the problem, help me pls and if u can use simplified english cause i am from Russia. Here is my code:
using System;
using System.Numerics;
using System.Collections.Generic;
public class ProdSeq
{
public static BigInteger[] solve(int[] arr)
{
bool simplified = false;
var result = new BigInteger[2];
var index = 0;
BigInteger sequenceSum = 1;
for (int i = 0; i < arr.Length - 1; i =2)
sequenceSum *= arr[i] * arr[i] arr[i 1] * arr[i 1];
if (sequenceSum >= 1000000)
{
sequenceSum /= 10000;
simplified = true;
}
var list = new List<BigInteger>();
for (BigInteger i = 0; i <= (BigInteger)Math.Sqrt((double)sequenceSum 1); i )
list.Add(BigInteger.Multiply(i, i));
for (int i = 0; i < list.Count; i )
{
var second = sequenceSum - list[i];
index = list.BinarySearch(second);
if (index > -1)
{
if (simplified)
{
result[0] = (BigInteger)(Math.Sqrt((double)list[i]) * 100);
result[1] = (BigInteger)(Math.Sqrt((double)list[index]) * 100);
break;
}
result[0] = (BigInteger)(Math.Sqrt((double)list[i]));
result[1] = (BigInteger)(Math.Sqrt((double)list[index]));
break;
}
}
Console.WriteLine($"A: {result[0]} B: {result[1]}");
return result;
}
}
CodePudding user response:
it seems your error is coming from this line:
for (int i = 0; i <= (int)Math.Sqrt((double)sequenceSum 1); i )
list.Add(BigInteger.Multiply(i , i));
you have to use Biginteger.Multiply method
result = 302400 and 29092800 (lot of solutions i think)
