I'm trying to find GRC for N numbers. For example N = 4, so the 4 numbers is for example 199 199 -199 -199. And im getting StackOverflowException for those numbers. Why?
first input number of integers for which i should find GRC.
Second input number is array of numbers wroted in one line separeted by " ".
Here is my code:
static int GCD(int a, int b)
{
if (b == 0) return a;
if (a > b) return GCD(b, a - b);
else return GCD(a, b-a);
}
static void Main()
{
var input = Convert.ToInt32(Console.ReadLine());
int gcd;
string readLine = Console.ReadLine();
string[] stringArray = readLine.Split(' ');
int[] intArray = new int[input];
for (int i = 0; i < stringArray.Length; i++)
{
intArray[i] = int.Parse(stringArray[i]);
}
if (input >= 2)
{
gcd= Math.Abs(GCD(intArray[0], intArray[1]));
}
else
{
gcd= intArray[0];
}
for (int i = 2; i < input; i++)
{
gcd= Math.Abs(GCD(gcd, intArray[i]));
}
Console.WriteLine(Math.Abs(gcd));
Console.ReadKey();
}
Any suggestions how to improve the code?
First of all, it's unclear what is GRC. Your code is about GCD - Greatest Common Divisor. Let's improve its implementation.
If you have huge difference, beween a and b, say a = 1_000_000_000 and b = 1 you
are going to have ~ a - b ~ 1_000_000_000 recursive calls in GCD and have Stack Overflow Exception.
Let's use modulo arithmetics instead: if a = b + b + ... + b + remainder, we can find remainder in one go, without subtracting b: remainder = a % b
Code:
static int GCD(int a, int b)
{
a = Math.Abs(a);
b = Math.Abs(b);
if (a == 0)
return b; // b divides both 0 and itself
if (b == 0)
return a; // a divides both 0 and itself
if (a % b == 0) // b divides both a and b, so b is GCD(a, b)
return b;
return GCD(b, a % b);
}
then we can compute GCD for as many numbers as we want
static int GCD(IEnumerable<int> numbers) {
if (numbers is null)
throw new ArgumentNullException(nameof(numbers));
int result = 0;
foreach (var number in numbers)
if (result == 0)
result = number;
else
result = GCD(result, number);
return result != 0
? result
: throw new ArgumentOutOfRangeException(nameof(numbers), "Empty sequence");
}
Usage: (fiddle)
using System.Linq;
...
static void Main() {
int gcd = GCD(Console
.ReadLine()
.Split(' ', StringSplitOptions.RemoveEmptyEntries)
.Select(item => int.Parse(item)));
Console.Write(gcd);
}
I'm trying to calculate the cumulative binomial probability of 'n' trials, with 'p' probability and 'r' as the successful outcome of each trial. I have written the following code that works sometimes, but not always:
Console.WriteLine ();
Console.WriteLine ("B~(n, p)");
incorrectN:
Console.WriteLine ("Enter value of 'n': ");
int n = Convert.ToInt32 (Console.ReadLine ());
if (n < 0) {
Console.WriteLine ("ERROR: 'n' must be greater than 0");
goto incorrectN;
}
incorrectP:
Console.WriteLine ();
Console.WriteLine ("Enter value of 'p': ");
double p = Convert.ToDouble (Console.ReadLine ());
if (p > 1) {
Console.WriteLine ();
Console.WriteLine ("ERROR: 'p' must be between 0 and 1");
goto incorrectP;
}
Console.WriteLine ();
incorrectS:
int r = GetR();
int k = r;
double binomTotal = 0;
for (int j = r + 1; j > 0; j--) {
int nCr = Factorial(n) / (Factorial(n - (r - k)) * Factorial(r - k));
binomTotal = binomTotal + nCr * Math.Pow(p, (r - k)) * Math.Pow(1 - p, (n - (r - k)));
k--;
}
Console.WriteLine();
Console.WriteLine(binomTotal);
P.S. I have written the GetR() and Factorial() functions elsewhere within the class, where GetR() asks the user for the value of 'r' and Factorial() is defined as follows:
public static int Factorial(int x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
I tested the code with values n = 10, p = 0.5 and r = 5 and the output is 0.623046875, which is correct. However, when I use n = 13, p = 0.35 and r = 7, I get 0.297403640622647 instead of 0.9538.
Any help would be much appreciated.
In addition to your own answer:
public static double Factorial(double x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
accepts a double parameter, which means that x is not restricted to be an integer.
So you could call your Factorial method like this.
var fac1 = Factorial(1.4);
var fac2 = Factorial(2.7);
However, this does not make sense since the factorial is defined only* for , meaning that
is undefined.
So, instead of using double and allowing for invalid inputs, you should be using long instead, which has a greater range than int.
public static long Factorial(long x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
* there are some cases where factorials can be used with real values as well - e.g. by using the gamma function - but I don't think they're relevant to your use case and therefore you should not allow invalid parameters.
Change:
public static int Factorial(int x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
To:
public static double Factorial(double x)
{
return x <= 1 ? 1 : x * Factorial(x - 1);
}
Because Factorial(13) is too large for Int32.
I'm trying to write a simple quadratic equation solver in C#, but for some reason it's not quite giving me the correct answers. In fact, it's giving me extremely large numbers as answers, usually well into the millions.
Could anyone please shed some light? I get the exact same answer for the positive root and the negative root as well. (Tried two different methods of math)
static void Main(string[] args)
{
int a;
int b;
int c;
Console.WriteLine("Hi, this is a Quadratic Equation Solver!");
Console.WriteLine("a-value: ");
try
{
a = int.Parse(Console.ReadLine());
Console.WriteLine("b-value: ");
b = int.Parse(Console.ReadLine());
Console.WriteLine("c-value: ");
c = int.Parse(Console.ReadLine());
Console.WriteLine("Okay, so your positive root is: " + quadForm(a, b, c, true));
Console.WriteLine("And your negative root is: " + quadForm(a, b, c, false));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.ReadLine();
}
static int quadForm(int a, int b, int c, Boolean pos)
{
int x = 0;
if (pos)
x = ((-b + (int) (Math.Sqrt((b * b) - (4 * a * c)))) / (2 * a));
else
x = ((-Math.Abs(b) - (int) (Math.Sqrt(Math.Pow(b,2) - (4 * a * c)))) / (2 * a));
return x;
}
Try this version of quadForm:
static double quadForm(int a, int b, int c, bool pos)
{
var preRoot = b * b - 4 * a * c;
if (preRoot < 0)
{
return double.NaN;
}
else
{
var sgn = pos ? 1.0 : -1.0;
return (sgn * Math.Sqrt(preRoot) - b) / (2.0 * a);
}
}
There are several questions on Stack Overflow discussing how to find the Greatest Common Divisor of two values. One good answer shows a neat recursive function to do this.
But how can I find the GCD of a set of more than 2 integers? I can't seem to find an example of this.
Can anyone suggest the most efficient code to implement this function?
static int GCD(int[] IntegerSet)
{
// what goes here?
}
And here you have code example using LINQ and GCD method from question you linked. It is using theoretical algorithm described in other answers ... GCD(a, b, c) = GCD(GCD(a, b), c)
static int GCD(int[] numbers)
{
return numbers.Aggregate(GCD);
}
static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
You could use this common property of a GCD:
GCD(a, b, c) = GCD(a, GCD(b, c)) = GCD(GCD(a, b), c) = GCD(GCD(a, c), b)
Assuming you have GCD(a, b) already defined it is easy to generalize:
public class Program
{
static void Main()
{
Console.WriteLine(GCD(new[] { 10, 15, 30, 45 }));
}
static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
static int GCD(int[] integerSet)
{
return integerSet.Aggregate(GCD);
}
}
Wikipedia:
The gcd is an associative function:
gcd(a, gcd(b, c)) = gcd(gcd(a, b), c).
The gcd of three numbers can be computed as gcd(a, b, c) = gcd(gcd(a, b), c), or in some
different way by applying commutativity and associativity. This can be extended to any number of numbers.
Just take the gcd of the first two elements, then calculate the gcd of the result and the third element, then calculate the gcd of the result and fourth element...
Here's the C# version.
public static int Gcd(int[] x) {
if (x.length < 2) {
throw new ArgumentException("Do not use this method if there are less than two numbers.");
}
int tmp = Gcd(x[x.length - 1], x[x.length - 2]);
for (int i = x.length - 3; i >= 0; i--) {
if (x[i] < 0) {
throw new ArgumentException("Cannot compute the least common multiple of several numbers where one, at least, is negative.");
}
tmp = Gcd(tmp, x[i]);
}
return tmp;
}
public static int Gcd(int x1, int x2) {
if (x1 < 0 || x2 < 0) {
throw new ArgumentException("Cannot compute the GCD if one integer is negative.");
}
int a, b, g, z;
if (x1 > x2) {
a = x1;
b = x2;
} else {
a = x2;
b = x1;
}
if (b == 0) return 0;
g = b;
while (g != 0) {
z= a % g;
a = g;
g = z;
}
return a;
}
}
Source http://www.java2s.com/Tutorial/Java/0120__Development/GreatestCommonDivisorGCDofpositiveintegernumbers.htm
Rewriting this as a single function...
static int GCD(params int[] numbers)
{
Func<int, int, int> gcd = null;
gcd = (a, b) => (b == 0 ? a : gcd(b, a % b));
return numbers.Aggregate(gcd);
}
gcd(a1,a2,...,an)=gcd(a1,gcd(a2,gcd(a3...(gcd(a(n-1),an))))), so I would do it just step by step aborting if some gcd evaluates to 1.
If your array is sorted, it might be faster to evaluate gcd for small numbers earlier, since then it might be more likely that one gcd evaluates to 1 and you can stop.
int GCD(int a,int b){
return (!b) ? (a) : GCD(b, a%b);
}
void calc(a){
int gcd = a[0];
for(int i = 1 ; i < n;i++){
if(gcd == 1){
break;
}
gcd = GCD(gcd,a[i]);
}
}
/*
Copyright (c) 2011, Louis-Philippe Lessard
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
unsigned gcd ( unsigned a, unsigned b );
unsigned gcd_arr(unsigned * n, unsigned size);
int main()
{
unsigned test1[] = {8, 9, 12, 13, 39, 7, 16, 24, 26, 15};
unsigned test2[] = {2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048};
unsigned result;
result = gcd_arr(test1, sizeof(test1) / sizeof(test1[0]));
result = gcd_arr(test2, sizeof(test2) / sizeof(test2[0]));
return result;
}
/**
* Find the greatest common divisor of 2 numbers
* See http://en.wikipedia.org/wiki/Greatest_common_divisor
*
* #param[in] a First number
* #param[in] b Second number
* #return greatest common divisor
*/
unsigned gcd ( unsigned a, unsigned b )
{
unsigned c;
while ( a != 0 )
{
c = a;
a = b%a;
b = c;
}
return b;
}
/**
* Find the greatest common divisor of an array of numbers
* See http://en.wikipedia.org/wiki/Greatest_common_divisor
*
* #param[in] n Pointer to an array of number
* #param[in] size Size of the array
* #return greatest common divisor
*/
unsigned gcd_arr(unsigned * n, unsigned size)
{
unsigned last_gcd, i;
if(size < 2) return 0;
last_gcd = gcd(n[0], n[1]);
for(i=2; i < size; i++)
{
last_gcd = gcd(last_gcd, n[i]);
}
return last_gcd;
}
Source code reference
let a = 3
let b = 9
func gcd(a:Int, b:Int) -> Int {
if a == b {
return a
}
else {
if a > b {
return gcd(a:a-b,b:b)
}
else {
return gcd(a:a,b:b-a)
}
}
}
print(gcd(a:a, b:b))
GCD(a, b, c) = GCD(a, GCD(b, c)) = GCD(GCD(a, b), c) = GCD(GCD(a, c), b)
public class Program {
static void Main() {
Console.WriteLine(GCD(new [] {
10,
15,
30,
45
}));
}
static int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}
static int GCD(int[] integerSet) {
return integerSet.Aggregate(GCD);
}
}
These are the three most common used:
public static uint FindGCDModulus(uint value1, uint value2)
{
while(value1 != 0 && value2 != 0) {
if (value1 > value2) {
value1 %= value2;
} else {
value2 %= value1;
}
}
return Math.Max(value1, value2);
}
public static uint FindGCDEuclid(uint value1, uint value2)
{
while(value1 != 0 && value2 != 0) {
if (value1 > value2) {
value1 -= value2;
} else {
value2 -= value1;
}
}
return Math.Max(value1, value2);
}
public static uint FindGCDStein(uint value1, uint value2)
{
if (value1 == 0) return value2;
if (value2 == 0) return value1;
if (value1 == value2) return value1;
bool value1IsEven = (value1 & 1u) == 0;
bool value2IsEven = (value2 & 1u) == 0;
if (value1IsEven && value2IsEven) {
return FindGCDStein(value1 >> 1, value2 >> 1) << 1;
} else if (value1IsEven && !value2IsEven) {
return FindGCDStein(value1 >> 1, value2);
} else if (value2IsEven) {
return FindGCDStein(value1, value2 >> 1);
} else if (value1 > value2) {
return FindGCDStein((value1 - value2) >> 1, value2);
} else {
return FindGCDStein(value1, (value2 - value1) >> 1);
}
}
By using this, you can pass multiple values as well in the form of array:-
// pass all the values in array and call findGCD function
int findGCD(int arr[], int n)
{
int gcd = arr[0];
for (int i = 1; i < n; i++) {
gcd = getGcd(arr[i], gcd);
}
return gcd;
}
// check for gcd
int getGcd(int x, int y)
{
if (x == 0)
return y;
return gcd(y % x, x);
}
I use int.MaxValue as a penalty and sometimes I am computing the penalties together. Is there a function or how would you create one with the most grace and efficiency that does that.
ie.
50 + 100 = 150
int.Max + 50 = int.Max and not int.Min + 50
This answer...
int penaltySum(int a, int b)
{
return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}
fails the following test:
[TestMethod]
public void PenaltySumTest()
{
int x = -200000;
int y = 200000;
int z = 0;
Assert.AreEqual(z, penaltySum(x, y));
}
I would suggest implementing penaltySum() as follows:
private int penaltySum(int x, int y, int max)
{
long result = (long) x + y;
return result > max ? max : (int) result;
}
Notice I'm passing in the max value, but you could hardcode in the int.MaxValue if you would like.
Alternatively, you could force the arithmetic operation overflow check and do the following:
private int penaltySum(int x, int y, int max)
{
int result = int.MaxValue;
checked
{
try
{
result = x + y;
}
catch
{
// Arithmetic operation resulted in an overflow.
}
}
return result;
}
int penaltySum(int a, int b)
{
return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}
Update: If your penalties can be negative, this would be more appropriate:
int penaltySum(int a, int b)
{
if (a > 0 && b > 0)
{
return (int.MaxValue - a < b) ? int.MaxValue : a + b;
}
if (a < 0 && b < 0)
{
return (int.MinValue - a > b) ? int.MinValue : a + b;
}
return a + b;
}
Does it overflow a lot, or is that an error condition? How about using try/catch (overflow exception)?