C# % throws DivideByZeroException [closed] - c#

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
public static List<int> getDenoms(long n)
{
List<int> result = new List<int>();
for (int i = 1; i < n; i++)
{
if (n % i == 0)
{
result.Add(i);
}
}
return result;
}
public static int getHighestPrime(List<int> seq)
{
int currentHigh = 1;
foreach (int number in seq)
{
List<int> temp = getDenoms(number);
if (temp.Count == 1)
{
if (number > currentHigh)
{
currentHigh = number;
}
}
}
return currentHigh;
}
I have the current code going in C#. So, I have the two methods. In the getDenoms method, I assumed that the statement n%i would not throw any errors since i is greater than or equal to 1, but it does indeed throw that error.
I used the two methods in the following manner:
Console.WriteLine(getHighestPrime(getDenoms(600851475143)));
Any insight on why the code is throwing that error?

The reason is that 600851475143 is too big for an int!
Your looping variable i is an int, but you compare it to a long. 600851475143 is greater than int.MaxValue, so i eventually overflows and restarts at int.MinValue. Then it increases until it's 0 again and voilá:
DivideByZeroException
To solve this change the type of your loop variable to long, too:
for (long i = 1; i < n; i++)

'i' is a int as 'n' is long, so in the for cicle 'i' overflows and after a while reaches the '0' value.
Fix:
for (long i = 1; i < n; i++)

I have not tested this myself, but when I look at your code I see that your loop is using an int variable while your input is a long. The number that you are testing your function with, namely 600851475143, is larger than what an 32-bit int can represent. Try changing your variable i to long.

The reason for the failure is that your value 600851475143 is larger than int.MaxValue to solve this problem go ahead and use long instead of int
Note that long.MaxValue is: 9223372036854775807
See code below
public static List<long> getDenoms(long n)
{
List<long> result = new List<long>();
for (long i = 1; i < n; i++)
{
if (n % i == 0)
{
result.Add(i);
}
}
return result;
}
public static long getHighestPrime(List<long> seq)
{
int currentHigh = 1;
foreach (long number in seq)
{
List<long> temp = getDenoms(number);
if (temp.Count == 1)
{
if (number > currentHigh)
{
currentHigh = number;
}
}
}
return currentHigh;
}

Related

How do you find the positive sum of an array that also has negative numbers? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
public static int PositiveSum(int[] arr)
{
int sum = 0;
for(int i = 0; i > arr.Length; i++)
{
sum+=arr[i];
}
return sum;
}
Example:
[1,-4,7,12] => 1 + 7 + 12 = 20
Note: if there is nothing to sum, the sum defaults to 0.
One way, with minimum changes to your code, is to add a condition inside the for loop that sums the values allowing only positive numbers to be added.
Something you must change is the condition in the loop, i > arr.Length will break the cycle immediately, even if Length is 0, it needs to be i < arr.Length.
public static int PositiveSum(int[] arr)
{
int sum = 0;
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] > 0)
sum += arr[i];
}
return sum;
}
I would try filtering the arr to only contain positive numbers, then use sum on that new list:
public static int PositiveSum(int[] arr)
{
var pos = arr.Where(x => x > 0);
int sum = pos.Sum();
return sum;
}

New Year Chaos HackerRank Practise Problem - C# solution optimization [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
static void minimumBribes(int[] q)
{
Int32 TotalCount = 0;
bool blnSuccess = true;
Int32[] size = Ordering(q);
for (int intI = 0; intI < q.Length; intI++)
{
Int32 Tempvariable = 0;
Int32 TooChaotic = 0;
Int32 index = Index(size,q[intI]);
do
{
if (q[intI] != size[intI])
{
Tempvariable = size[index];
size[index] = size[index - 1];
size[index - 1] = Tempvariable;
index = index - 1;
TooChaotic = TooChaotic + 1;
if (TooChaotic > 2)
{
break;
}
TotalCount = TotalCount + 1;
}
} while (q[intI] != size[intI]);
if (TooChaotic > 2)
{
Console.WriteLine("Too chaotic");
blnSuccess = false;
break;
}
}
if (blnSuccess)
{
Console.WriteLine(TotalCount);
}
}
static int[] Ordering(int[] z)
{
int[] r = new int[z.Length];
r = z.OrderBy(x => x).ToArray();
return r;
}
static int Index(int[] z,int integer)
{
for (int intI = 0; intI < z.Length; intI++)
{
if(z[intI]== integer)
{
return intI;
}
}
return 0;
}
This code is working fine, but its runtime is too long.
I'm getting "Terminated due to timeout" in HackerRank. However, the solution is working fine on the local computer but it's taking more time.
Problem Link:https://www.hackerrank.com/challenges/new-year-chaos/problem.
Sample Input
2 (the number of test cases)
5 (number of people in the queue)
2 1 5 3 4 (n space-separated integers describing the final state of the queue)
5 (number of people in the queue)
2 5 1 3 4 (n space-separated integers describing the final state of the queue).
It must print an integer representing the minimum number of bribes necessary, or Too chaotic if the line configuration is not possible.
Output
3
Too chaotic
Question:
How do I reduce its runtime? Presently, I am using an array.
I've solved it a few weeks ago, this is my solution to the problem (100%)
static void minimumBribes(int[] q) {
int bribe = 0;
bool chaotic = false;
int n = q.Length;
for(int i = 0; i < n; i++)
{
if(q[i]-(i+1) > 2)
{
chaotic = true;
break;
}
for (int j = Math.Max(0, q[i]-2); j < i; j++)
if (q[j] > q[i])
bribe++;
}
if(chaotic)
Console.WriteLine("Too chaotic");
else
Console.WriteLine(bribe);
}
You don't need any other methods than the one provided by the challenge

Why do I need Iterators in real life? Without built in C# collection types [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have 2 realizations of a method that calculates Fibonacci numbers. Why would I need an iterator realization in real life nor the Fibonacci example? Cause I can't see the difference. Yes, I know about Interfaces but I need a real example where iterators are useful, not just in built-in collection types. Why do I need the Fibo iterator method if I can do like in the Fibonacci method?
using System;
using System.Collections.Generic;
class Fibonacci_C
{
static void Main()
{
foreach (int fib in Fibo(5))
{
Console.WriteLine(fib);
}
Console.ReadLine();
for (int i = 0; i < 5; i++)
{
Console.WriteLine(Fibonacci(i));
}
Console.ReadLine();
}
static public IEnumerable<int> Fibo(int length)
{
int prevFib = 0, curFib = 1, newFib = 0;
for (int i = 0; i < length; i++)
{
yield return prevFib;
newFib = prevFib + curFib;
prevFib = curFib;
curFib = newFib;
}
}
public static int Fibonacci(int length)
{
int a = 0;
int b = 1;
for (int i = 0; i < length; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return a;
}
}
In your example, the iterator saves you from calculating already calculated fibonacci numbers over and over again. Your second method
public static int Fibonacci(int length)
{
int a = 0;
int b = 1;
for (int i = 0; i < length; i++)
{
int temp = a;
a = b;
b = temp + b;
}
return a;
}
when called in the for loop, has to calculate all fibonacci numbers up to Fib(length) on each call, even though it has already calculated them in previous calls. Your iterator method spares you that since it only calculates each fibonacci number once, and returns it using yield return.
Iterators are not the sole way of avoiding unnecessary recalculation, though.

C# Get max difference from 7 integers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have problem with getting the difference between the lowest and highest entered integer. This is my code so far, but I don't understand why I keep getting error messages.
using System;
class Program
{
public static int array(int[] numbers)
{
int minint = array(numbers);
int maxint = array(numbers);
foreach (int value in array(numb)
{
if (value < minint) minint = value;
if (value > maxint) maxint = value;
}
return maxint - minint;
}
static void Main(string[] args)
{
int[] numbers = new int[7];
for (int i = 0; i < 7; i++)
{
Console.Write("Enter number {0}: ", i + 1);
numbers[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("Difference between min and max is: {0} ", array(numbers));
Console.ReadLine();
}
}
i'd go with the existing methods Min() and Max()
public static int array(int[] numbers)
{
return numbers.Max() - numbers.Min();
}
otherwise your array method should look like this
public static int array(int[] numbers)
{
int minint = numbers[0];
int maxint = numbers[0];
foreach (int value in numbers)
{
if (value < minint) minint = value;
if (value > maxint) maxint = value;
}
return maxint - minint;
}
usually the difference is ment to be a positive value - so you should take the absolute value Math.Abs() or item = item < 0 ? -item : item; in case of negative numbers within your array

Project Euler - Number 2 - C#

I'm quite new to programming in C#, and thought that attempting the Euler Problems would be a good idea as a starting foundation. However, I have gotten to a point where I can't seem to get the correct answer for Problem 2.
"Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms."
My code is this:
int i = 1;
int j = 2;
int sum = 0;
while (i < 4000000)
{
if (i < j)
{
i += j;
if (i % 2 == 0)
{
sum += i;
}
}
else
{
j += i;
if (j % 2 == 0)
{
sum += j;
}
}
}
MessageBox.Show("The answer is " + sum);
Basically, I think that I am only getting the last two even numbers of the sequence and adding them - but I don't know how to get all of the even numbers of the sequence and add them. Could someone please help me, whilst trying to progress from my starting point?
P.S. - If there are any really bad layout choices, do say as eliminating these now will help me to become a better programmer in the future :)
Thanks a lot in advance.
I just logged in into my Project Euler account, to see the correct answer. As others say, you forgot to add the initial term 2, but otherwise your code is OK (the correct answer is what your code outputs + 2), so well done!
It is pretty confusing though, I think it would look way clearer if you'd use 3 variables, something like:
int first = 1;
int second = 1;
int newTerm = 0;
int sum = 0;
while (newTerm <= 4000000)
{
newTerm = first + second;
if (newTerm % 2 == 0)
{
sum += newTerm;
}
first = second;
second = newTerm;
}
MessageBox.Show("The answer is " + sum);
You need to set the initial value of sum to 2, as you are not including that in your sum with the current code.
Also, although it may be less efficient memory-usage-wise, I would probably write the code something like this because IMO it's much more readable:
var fibonacci = new List<int>();
fibonacci.Add(1);
fibonacci.Add(2);
var curIndex = 1;
while(fibonacci[curIndex] + fibonacci[curIndex - 1] <= 4000000) {
fibonacci.Add(fibonacci[curIndex] + fibonacci[curIndex - 1]);
curIndex++;
}
var sum = fibonacci.Where(x => x % 2 == 0).Sum();
Use an array fib to store the sequence. Its easier to code and debug. At every iteration, you just need to check if the value is even.
fib[i] = fib[i - 1] + fib[i - 2];
if (fib[i] > 4000000) break;
if (fib[i] % 2 == 0) sum += fib[i];
I've solved this a few years ago, so I don't remember how I did it exactly, but I do have access to the forums talking about it. A few hints and an outright solution. The numbers repeat in a pattern. two odds followed by an even. So you could skip numbers without necessarily doing the modulus operation.
A proposed C# solution is
long sum = 0, i0, i1 = 1, i2 = 2;
do
{
sum += i2;
for (int i = 0; i < 3; i++)
{
i0 = i1;
i1 = i2;
i2 = i1 + i0;
}
} while (i2 < 4000000);
Your code is a bit ugly, since you're alternating between i and j. There is a much easier way to calculate fibonacci numbers by using three variables and keeping their meaning the same all the time.
One related bug is that you only check the end condition on every second iteration and in the wrong place. But you are lucky that the cutoff fit your bug(the number that went over the limit was odd), so this is not your problem.
Another bug is that you check with < instead of <=, but since there is no fibonacci number equal to the cutoff this doesn't cause your problem.
It's not an int overflow either.
What remains is that you forgot to look at the first two elements of the sequence. Only one of which is even, so you need to add 2 to your result.
int sum = 0; => int sum = 2;
Personally I'd write one function that returns the infinite fibonacci sequence and then filter and sum with Linq. Fibonacci().TakeWhile(i=> i<=4000000).Where(i=>i%2==0).Sum()
I used a class to represent a FibonacciNumber, which i think makes the code more readable.
public class FibonacciNumber
{
private readonly int first;
private readonly int second;
public FibonacciNumber()
{
this.first = 0;
this.second = 1;
}
private FibonacciNumber(int first, int second)
{
this.first = first;
this.second = second;
}
public int Number
{
get { return first + second; }
}
public FibonacciNumber Next
{
get
{
return new FibonacciNumber(this.second, this.Number);
}
}
public bool IsMultipleOf2
{
get { return (this.Number % 2 == 0); }
}
}
Perhaps it's a step too far but the end result is a function which reads quite nicely IMHO:
var current = new FibonacciNumber();
var result = 0;
while (current.Number <= max)
{
if (current.IsMultipleOf2)
result += current.Number;
current = current.Next;
}
return result;
However it's not going to be as efficient as the other solutions which aren't newing up classes in a while loop. Depends on your requirements I guess, for me I just wanted to solve the problem and move on to the next one.
Hi i have solved this question, check it if its right.
My code is,
#include<iostream.h>
#include<conio.h>
class euler2
{
unsigned long long int a;
public:
void evensum();
};
void euler2::evensum()
{
a=4000000;
unsigned long long int i;
unsigned long long int u;
unsigned long long int initial=0;
unsigned long long int initial1=1;
unsigned long long int sum=0;
for(i=1;i<=a;i++)
{
u=initial+initial1;
initial=initial1;
initial1=u;
if(u%2==0)
{
sum=sum+u;
}
}
cout<<"sum of even fibonacci numbers upto 400000 is"<<sum;
}
void main()
{
euler2 a;
clrscr();
a.evensum();
getch();
}
Here's my implementation:
public static int evenFibonachi(int n)
{
int EvenSum = 2, firstElem = 1, SecondElem = 2, SumElem=0;
while (SumElem <= n)
{
swich(ref firstElem, ref SecondElem, ref SumElem);
if (SumElem % 2 == 0)
EvenSum += SumElem;
}
return EvenSum;
}
private static void swich(ref int firstElem, ref int secondElem, ref int SumElem)
{
int temp = firstElem;
firstElem = secondElem;
secondElem += temp;
SumElem = firstElem + secondElem;
}

Categories

Resources