C# Raise number to power [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 2 years ago.
Improve this question
I recently stumbled upon a weird bug in one of my programs.
for (int i = 0; i < bitArray.Length; i++)
{
if (bitArray[i])
{
returnValue = returnValue + 2 ^ (7 - i);
}
}
In the snippet above, if returnValue = 0, by the time it reaches a set bit at i = 7, the resulting output is 2, which makes no sense (2^0 should be 1). However if I replace the code with:
returnValue = returnValue + Convert.ToInt32(Math.Pow(2,(7 - i)));
It is evaluated correctly to returnValue = 1
The problem is solved by using Math.Pow(), but I would very much like to know why it happens in the initial code.

In C# (and many other languages) the ^ operator is the boolean logical XOR.
See this document for more information about boolean operators in C#.

In addition to the other answers, it is probably simplest if you just use the C# left-shift operator <<, assuming bitArray.Length is less than or equal to 8:
for (int i = 0; i < bitArray.Length; i++)
{
if (bitArray[i])
{
returnValue = returnValue + 1 << (7 - i);
}
}
If returnValue is a float type and the intention is to allow negative powers of 2, then a slight change yields:
for (int i = 0; i < bitArray.Length; i++)
{
if (bitArray[i])
{
returnValue = returnValue + ((7-i) >= 0) ? 1 << (7 - i) : 1.0 / ((1 << (7 - i));
}
}
although in this case Math.Pow(2, 7 - i) is much cleaner.
for (int i = 0; i < bitArray.Length; i++)
{
if (bitArray[i])
{
returnValue = returnValue + Math.Pow(2, 7 - i);
}
}

As #IshaySela and #Adomas have said, ^ is a bollean logical XOR.
But in-order to do what you want to do without using math.pow() you can just make an if condition to check if the power is equal ZERO or not.
if (bitArray[i]) {
if ((7 - i) == 0){
//returnValue += 1;
}
else{
//returnValue += 2 ^ (7 - i);
}
}

Related

C# % throws DivideByZeroException [closed]

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;
}

Errors when using quicksort to sort a double [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
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.
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.
Improve this question
I have a string array that I convert to double, I pass it into the following quicksort algorithm and get multiple errors saying I cannot onvert double to int despite having a double array. Left and right are 0 and arr.Length - 1 respectively.
public static double[] quick_Sort(double[] arr, double left, double right)
{
double i, j;
double pivot, temp;
i = left;
j = right;
pivot = arr[(left + right) / 2];
do
{
while ((arr[i] < pivot) && (i < right)) i++;
while ((pivot < arr[j]) && (j > left)) j--;
if (i <= j)
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
} while (i <= j);
if (left < j) quick_Sort(arr, left, j);
if (i < right) quick_Sort(arr, i, right);
return arr;
}
The problem is that you are using doubles for your array indexes -- which are supposed to be ints, e.g.
arr[i]
You need to use int values for your indexes, e.g.:
int i;
i = Convert.ToInt32(left);
Or just use int instead of double for your all your variables (depending on how your program works). I'm not sure what's best without more information.

List of Non-Negative Integers - concatenate into largest possible nr - e.g. [1,2,5] = 521 [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 7 years ago.
Improve this question
I'm following this blog asking
Five programming problems every Software Engineer should be able to solve in less than 1 hour
I am absolutely stumped by question 4 (5 is a different story too)
Write a function that given a list of non negative integers, arranges them such that they form the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021.
Now the author posted a answer, and I saw an python attempt too:
import math
numbers = [50,2,1,9,10,100,52]
def arrange(lst):
for i in xrange(0, len(lst)):
for j in xrange(0, len(lst)):
if i != j:
comparison = compare(lst[i], lst[j])
if lst[i] == comparison[0]:
temp = lst[j]
lst[j] = lst[i]
lst[i] = temp
return lst
def compare(num1, num2):
pow10_1 = math.floor(math.log10(num1))
pow10_2 = math.floor(math.log10(num2))
temp1 = num1
temp2 = num2
if pow10_1 > pow10_2:
temp2 = (temp2 / math.pow(10, pow10_2)) * math.pow(10, pow10_1)
elif pow10_2 > pow10_1:
temp1 = (temp1 / math.pow(10, pow10_1)) * math.pow(10, pow10_2)
print "Starting", num1, num2
print "Comparing", temp1, temp2
if temp1 > temp2:
return [num1, num2]
elif temp2 > temp1:
return [num2, num1]
else:
if num1 < num2:
return [num1, num2]
else:
return [num2, num1]
print arrange(numbers)
but I'm not going to learn these languages soon. Is anyone willing to share how they would sort the numbers in C# to form the largest number please?
I've also tried straight conversion to C# in VaryCode but when the IComparer gets involved, then it causes erroneous conversions.
The python attempt uses a bubble sort it seems.
Is bubble sort a starting point? What else would be used?
The solution presented uses the approach to sort the numbers in the array in a special way. For example the value 5 comes before 50 because "505" ("50"+"5") comes before "550" ("5"+"50"). The thinking behind this isn't explained, and I'm not convinced that it actually works...
When looking that the problem, I came to this solution:
You can do it recursively. Make a method that loops through the numbers in the array and concatenates each number with the largest value that can be formed by the remaining numbers, to see which one of those is largest:
public static int GetLargest(int[] numbers) {
if (numbers.Length == 1) {
return numbers[0];
} else {
int largest = 0;
for (int i = 0; i < numbers.Length; i++) {
int[] other = numbers.Take(i).Concat(numbers.Skip(i + 1)).ToArray();
int n = Int32.Parse(numbers[i].ToString() + GetLargest(other).ToString());
if (i == 0 || n > largest) {
largest = n;
}
}
return largest;
}
}
If you want to do it by bubble sort, try this:
public static void Main()
{
bool swapped = true;
while (swapped)
{
swapped = false;
for (int i = 0; i < VALUES.Length - 1; i++)
{
if (Compare(VALUES[i], VALUES[i + 1]) > 0)
{
int temp = VALUES[i];
VALUES[i] = VALUES[i + 1];
VALUES[i + 1] = temp;
swapped = true;
}
}
}
String result = "";
foreach (int integer in VALUES)
{
result += integer.ToString();
}
Console.WriteLine(result);
}
public static int Compare(int lhs, int rhs)
{
String v1 = lhs.ToString();
String v2 = rhs.ToString();
return (v1 + v2).CompareTo(v2 + v1) * -1;
}
The Compare method compares the order of two numbers that would create the largest number. When it returns value larger than 0, that means you need to swap.
This is the sorting part:
while (swapped)
{
swapped = false;
for (int i = 0; i < VALUES.Length - 1; i++)
{
if (Compare(VALUES[i], VALUES[i + 1]) > 0)
{
int temp = VALUES[i];
VALUES[i] = VALUES[i + 1];
VALUES[i + 1] = temp;
swapped = true;
}
}
}
It checks to consecutive values in the array and swaps if necessary. After one iteration without swapping, the sort is finished.
Finally, you concatenate the values in the array and print it out.

Find numbers that don't divide by 3 or 7 [closed]

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 9 years ago.
Improve this question
I need help with a program.
I need to write a program that prints on the console numbers from 1 to N that can't divide in the same time by 3 or 7. I need to parse N so the user inputs a value for it. Here is my code for now, can you tell me what is wrong?
Console.Write("Enter a number: ");
int n = int.Parse(Console.ReadLine());
for (n = 1; n <= 99999; n++) {
//n % (3 * 7) == 0
I thought out how I will check it but I can't think out how to make the other part. I think there is something wrong with my loop too. Can you give me some hints where I am mistaken and what I can do? Thank you!
You're getting N from the user then immediately overwriting it. Use a different variable for your loop:
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
// do stuff
You can use Modulus %
Console.Write("Enter a number: ");
string input = Console.ReadLine();
int n;
if (int.TryParse(input, out n))
{
for (int i = 1; i < n; i++)
{
if(i % 3 != 0 || i% 7!= 0) Console.WriteLine(i);
}
}
Your loop is wrong because your condition is wrong.It should be i < n, you are getting an input but then you overwriting it's value by n = 1;
Console.Write("Enter a number: ");
int n = int.Parse(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
if (i % 21 != 0) { Console.Write(i + " "); }
}
Example: http://ideone.com/ThASen

is my C# standard deviation code correct? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
So I'm trying to compute standard deviation in C# and I got the following code:
double M = 0.0;
double S = 0.0;
int period = Values.Length;
int k;
double tmpM;
double value;
for(int i = 0; i < period; i++){
tmpM = M;
value = Values[i];
k = i + 1;
M += (value - tmpM) / k;
S += (value - tmpM) * (value - M);
}
stdev = Math.Sqrt(S / (period - 1));
where Values is an array of data in which I'm trying to obtain the standard deviation
Do you think my code is correct or did I miss something?
Btw I was trying to implement this: http://www.johndcook.com/standard_deviation.html
It doesn't handle the case where period == 1 correctly. In that eventuality you will divide by zero.
Otherwise I believe your code to be correct.

Categories

Resources