Negative exponent of a number - c#

I made this program to find the power of any number using recursion and it works, but also I need to find negative power of the number, for example, I have the base = 2 and the exponent = -3 so the result = 0.125,
what should I do?
public static int power(int x, int n )
{
if (n < 0)
{
Console.WriteLine("invalid");
return 0;
}
else if (n == 1)
{
return x;
}
else if (n == 0)
{
return 1;
}
else
{
return x * power(x, n - 1);
}
}
static void Main(string[] args)
{
Console.Write("enter the base: ");
int x = int.Parse(Console.ReadLine());
Console.Write("enter the power:");
int n = int.Parse(Console.ReadLine());
int z = power(x, n);
Console.WriteLine(z);
}

Since the result of raising a number to a negative power is just 1 divided by the number raised to the non-negative power, you can change you method like so (note that we also need to return a double type, since we're dealing with fractional values):
public static double power(int x, int n)
{
if (n < 0) return 1 / power(x, -n); // recursive call with '-n' for negative powers
if (n == 0) return 1;
if (n == 1) return x;
return x * power(x, n - 1);
}
Now it works with negative numbers:
public static void Main(string[] args)
{
Console.WriteLine(power(2, -3));
GetKeyFromUser("\nDone! Press any key to exit...");
}
Output

Related

C# lottery 6 from 49 algorithm

I need to display odds to win with ten decimals if I play with just one variant, for six five and four numbers. For example I need to have this 0.0000000715 but I have this 0.0027829314 if I introduce 49,6,I. What is the problem?How can I make it work? I am a beginner and I don't know how i can obtain this 0.0000000715.
class Program
{
static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
int k = Convert.ToInt32(Console.ReadLine());
string category = Console.ReadLine();
switch (category)
{
case "I":
calculate(n,k);
break;
case "II":
calculate(n, k);
break;
case "III":
calculate(n, k);
break;
}
}
static void calculate(int n, int k)
{
int nk = n - k;
decimal count = prod(1, nk) / prod(k + 1, n);
decimal r = prod(1, k) / prod(n - k + 1, n);
decimal sum = count * r;
Console.WriteLine(Math.Round(r,10));
}
static decimal prod(int x, int y)
{
decimal prod = 0;
for(int i = x; i <= y; i++)
{
prod = x * y;
}
return prod;
}
}
The general solution would be bc(6,n)*bc(49-6,6-n)/bc(49, 6), where n is, 4, 5 or 6 and bc is the binomial coefficient.
Btw.: double should be enough for 10 decimal places, there is no need to use decimal.
using System;
public class Program
{
//bonomial coefficient
static double bc(double n, double k)
{
if (k == 0 || k == n)
return 1;
return bc(n - 1, k - 1) + bc(n - 1, k);
}
public static void Main()
{
for(int n = 4; n <=6; ++n){
Console.WriteLine(bc(6,n)*bc(49-6,6-n)/bc(49, 6));
}
}
}
I am not sur what function you were using.
The chances of winning all 6 numbers is 1 in 13,983,816
The actual calculation is this:
49C6 = 49!/(43! x 6!) = 13983816
So the probability to win is 1 / 13,983,816 = 0.0000000715
Your prod function should look like:
static decimal prod(int x, int y)
{
decimal prod = 1;
for(int i = x; i <= y; i++)
{
prod = prod * i;
}
return prod;
}
As jjj mentioned, you overwrite "prod" everytime, but you need to add it

Return value only of last iteration

I am trying to calculate the Greatest Common Divisor using a while loop. I am therefore looking for the greatest number (i.e. the last value of the loop). How do I get rid of the preceding numbers?
Example:
The greatest common divisor of 84 and 18 is 6. However, my code gives me the numbers 2, 3, and 6. What do I need to change to get only the last number?
using System;
namespace CalculateGCD
{
class Program
{
static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int i = 1;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
}
}
}
}
}
Define a variable called max then print the max out of the while loop like this:
int max = 0;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
max = i;
}
}
Console.WriteLine("GCD:{0}", max);
Also if you are using C# 6 you could simplify your Console.WriteLine by using string interpolation like this:
Console.WriteLine($"GCD:{max}");
There is a simple solution which will calculate GCD
static int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}
and you can use it like below
using System;
namespace CalculateGCD
{
public class Program
{
public static void Main(string[] args)
{
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
Console.WriteLine(GCD(a,b));
}
static int GCD(int a, int b)
{
return b == 0 ? a : GCD(b, a % b);
}
}
}
You can invert the loop, insted of going from 1 to the Min between a and b, search from the Min to 1.
int i = Math.Min(a, b);
while (i > 0)
{
i--;
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
break;
}
}
simply reverse the enumeration sequence will do
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int i = Math.Min(a ,b);
while (i > 1)
{
if (a % i == 0 && b % i == 0)
{
Console.WriteLine("GCD:{0}", i);
break;//greatest will be the first
}
i--;
}
int gcd;
while (i <= Math.Min(a, b))
{
i++;
if (a % i == 0 && b % i == 0)
{
gcd=i;
}
}
Console.WriteLine("GCD:{0}",gcd);
Save greatest common divisor in a variable.

Beginner - C# Fractional Calculator simplification of negative fractions

I've been having troubles trying to get my fractional calculator to work. I'm trying to get the simplifying to work, it works correctly simplifiyng positive fractions, but if I were to put a negative fraction it won't simplify it, I'm not sure what I'm doing wrong and I've read over it numerous times (the Gcd and Reduce functions).
Im new to all of this, any help appreciated.
My Reduce and GCD functions:
public int gcd()
{
// assigned x and y to the answer Numerator/Denominator, as well as an
// empty integer, this is to make code more simple and easier to read
int x = answerNumerator;
int y = answerDenominator;
int m;
// check if numerator is greater than the denominator,
// make m equal to denominator if so
if (x > y)
m = y;
else
// if not, make m equal to the numerator
m = x;
// assign i to equal to m, make sure if i is greater
// than or equal to 1, then take away from it
for (int i = m; i >= 1; i--)
{
if (x % i == 0 && y % i == 0)
{
//return the value of i
return i;
}
}
return 1;
}
public void Reduce()
{
try
{
//assign an integer to the gcd value
int gcdNum = gcd();
if (gcdNum != 0)
{
answerNumerator = answerNumerator / gcdNum;
answerDenominator = answerDenominator / gcdNum;
}
if (answerDenominator < 0)
{
answerDenominator = answerDenominator * -1;
answerNumerator = answerNumerator * -1;
}
}
catch (Exception exp)
{
// display the following error message
// if the fraction cannot be reduced
throw new InvalidOperationException(
"Cannot reduce Fraction: " + exp.Message);
}
}
I think the problem is that, when you determine the GCD, you are checking that the value is >= 1 in your for loop, even though it may be negative. In order to avoid this, you should capture the absolute values of the numerator and denominator when determining the GCD.
For example, this should fix it:
public int gcd()
{
// assigned x and y to the absolute values of the answer Numerator/Denominator,
// as well as an empty integer, this is to make code more simple and easier to read
int x = Math.Abs(answerNumerator);
int y = Math.Abs(answerDenominator);
int m;
// check if numerator is greater than the denominator,
// make m equal to denominator if so
if (x > y)
m = y;
else
// if not, make m equal to the numerator
m = x;
// assign i to equal to m, make sure if i is greater
// than or equal to 1, then take away from it
for (int i = m; i >= 1; i--)
{
if (x % i == 0 && y % i == 0)
{
//return the value of i
return i;
}
}
return 1;
}
Short Answer
You need:
int x = Math.Abs(answerNumerator);
int y = Math.Abs(answerDenominator);
Running Code
Here is a running Fiddle for you: https://dotnetfiddle.net/nBzr0i
Output:
Initial: 2/4
Reduced: 1/2
---
Initial: 2/-4
Reduced: -1/2
---
Running Code:
using System;
public class Program
{
public static void Main()
{
Calc.Reduce(2,4);
Calc.Reduce(2,-4);
}
}
public static class Calc
{
public static int gcd(int answerNumerator, int answerDenominator)
{
// assigned x and y to the answer Numerator/Denominator, as well as an
// empty integer, this is to make code more simple and easier to read
int x = Math.Abs(answerNumerator);
int y = Math.Abs(answerDenominator);
int m;
// check if numerator is greater than the denominator,
// make m equal to denominator if so
if (x > y)
m = y;
else
// if not, make m equal to the numerator
m = x;
// assign i to equal to m, make sure if i is greater
// than or equal to 1, then take away from it
for (int i = m; i >= 1; i--)
{
if (x % i == 0 && y % i == 0)
{
//return the value of i
return i;
}
}
return 1;
}
public static void Reduce(int answerNumerator, int answerDenominator)
{
Console.Write("Initial: ");
WriteFraction(answerNumerator, answerDenominator);
try
{
//assign an integer to the gcd value
int gcdNum = gcd(answerNumerator, answerDenominator);
if (gcdNum != 0)
{
answerNumerator = answerNumerator / gcdNum;
answerDenominator = answerDenominator / gcdNum;
}
if (answerDenominator < 0)
{
answerDenominator = answerDenominator * -1;
answerNumerator = answerNumerator * -1;
}
}
catch (Exception exp)
{
// display the following error message
// if the fraction cannot be reduced
throw new InvalidOperationException("Cannot reduce Fraction: " + exp.Message);
}
Console.Write("Reduced: ");
WriteFraction(answerNumerator, answerDenominator);
Console.WriteLine("---");
}
public static void WriteFraction(int answerNumerator, int answerDenominator)
{
Console.WriteLine(string.Format("{0}/{1}", answerNumerator, answerDenominator));
}
}

Adding 1/n^2+1/(n+1)^2+... in a loop

I'm quite new to programming so this shouldn't be a problem to most of you. I'm supposed to write a program which sums 1/n^2 (n being consecutive natural numbers) while elements are bigger than constant eps=0,001. I wrote a piece of code and tried to edit it but I'm still stuck in an infinite loop in which I just get consecutive numbers, but it's quite obvious the sum should be between 1 and 2. I'd be more than grateful if anyone could show me what it is that I'm doing wrong.
namespace program
{
class Program
{
static void Main(string[] args)
{
const double eps=0.001;
int n=1;
double x;
x = 1 / (n * n);
double sum=x;
while (x > eps)
{
n++;
sum = sum + x;
Console.WriteLine(sum);
}
Console.Write("\nSum: {0}.", sum);
Console.ReadLine();
}
}
}
You never recalculate the value of x, so the while condition never becomes false. If you move the assignment inside, your code won't loop forever.
const double eps=0.001;
int n=1;
double x;
double sum=x;
while (true)
{
x = 1.0 / (n * n);
if (x < eps) {
break;
}
n++;
sum = sum + x;
Console.WriteLine(sum);
}
Console.Write("\nSum: {0}.", sum);
Console.ReadLine();
A couple of things. First of all
1 / (n * n)
is an integer expression and is always either 0 or 1. You need to make it a floating point expression like this:
1.0 / (n * n)
And then you need to update x inside the loop rather than assigning to x once and once only.
Perhaps like this:
static void Main(string[] args)
{
const double eps = 0.001;
int n = 1;
double x = 1.0 / (n * n);
double sum = 0.0;
while (x > eps)
{
sum += x;
n++;
x = 1.0 / (n*n);
Console.WriteLine(sum);
};
Console.Write("\nSum: {0}", sum);
Console.ReadLine();
}
The downside of this is that the expression for x is written twice. So a better way is like this:
static void Main(string[] args)
{
const double eps = 0.001;
int n = 1;
double sum = 0.0;
while (true)
{
double x = 1.0 / (n * n);
if (x <= eps)
break;
sum += x;
n++;
Console.WriteLine(sum);
};
Console.Write("\nSum: {0}", sum);
Console.ReadLine();
}

Sum of digits in C#

What's the fastest and easiest to read implementation of calculating the sum of digits?
I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21
You could do it arithmetically, without using a string:
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
I use
int result = 17463.ToString().Sum(c => c - '0');
It uses only 1 line of code.
For integer numbers, Greg Hewgill has most of the answer, but forgets to account for the n < 0. The sum of the digits of -1234 should still be 10, not -10.
n = Math.Abs(n);
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
It the number is a floating point number, a different approach should be taken, and chaowman's solution will completely fail when it hits the decimal point.
public static int SumDigits(int value)
{
int sum = 0;
while (value != 0)
{
int rem;
value = Math.DivRem(value, 10, out rem);
sum += rem;
}
return sum;
}
int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;
I like the chaowman's response, but would do one change
int result = 17463.ToString().Sum(c => Convert.ToInt32(c));
I'm not even sure the c - '0', syntax would work? (substracting two characters should give a character as a result I think?)
I think it's the most readable version (using of the word sum in combination with the lambda expression showing that you'll do it for every char). But indeed, I don't think it will be the fastest.
I thought I'd just post this for completion's sake:
If you need a recursive sum of digits, e.g: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3
then the best solution would be
int result = input % 9;
return (result == 0 && input > 0) ? 9 : result;
int n = 17463; int sum = 0;
for (int i = n; i > 0; i = i / 10)
{
sum = sum + i % 10;
}
Console.WriteLine(sum);
Console.ReadLine();
I would suggest that the easiest to read implementation would be something like:
public int sum(int number)
{
int ret = 0;
foreach (char c in Math.Abs(number).ToString())
ret += c - '0';
return ret;
}
This works, and is quite easy to read. BTW: Convert.ToInt32('3') gives 51, not 3. Convert.ToInt32('3' - '0') gives 3.
I would assume that the fastest implementation is Greg Hewgill's arithmetric solution.
private static int getDigitSum(int ds)
{
int dssum = 0;
while (ds > 0)
{
dssum += ds % 10;
ds /= 10;
if (dssum > 9)
{
dssum -= 9;
}
}
return dssum;
}
This is to provide the sum of digits between 0-9
public static int SumDigits1(int n)
{
int sum = 0;
int rem;
while (n != 0)
{
n = Math.DivRem(n, 10, out rem);
sum += rem;
}
return sum;
}
public static int SumDigits2(int n)
{
int sum = 0;
int rem;
for (sum = 0; n != 0; sum += rem)
n = Math.DivRem(n, 10, out rem);
return sum;
}
public static int SumDigits3(int n)
{
int sum = 0;
while (n != 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
Complete code in: https://dotnetfiddle.net/lwKHyA
int j, k = 1234;
for(j=0;j+=k%10,k/=10;);
A while back, I had to find the digit sum of something. I used Muhammad Hasan Khan's code, however it kept returning the right number as a recurring decimal, i.e. when the digit sum was 4, i'd get 4.44444444444444 etc.
Hence I edited it, getting the digit sum correct each time with this code:
double a, n, sumD;
for (n = a; n > 0; sumD += n % 10, n /= 10);
int sumI = (int)Math.Floor(sumD);
where a is the number whose digit sum you want, n is a double used for this process, sumD is the digit sum in double and sumI is the digit sum in integer, so the correct digit sum.
static int SumOfDigits(int num)
{
string stringNum = num.ToString();
int sum = 0;
for (int i = 0; i < stringNum.Length; i++)
{
sum+= int.Parse(Convert.ToString(stringNum[i]));
}
return sum;
}
If one wants to perform specific operations like add odd numbers/even numbers only, add numbers with odd index/even index only, then following code suits best. In this example, I have added odd numbers from the input number.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Please Input number");
Console.WriteLine(GetSum(Console.ReadLine()));
}
public static int GetSum(string num){
int summ = 0;
for(int i=0; i < num.Length; i++){
int currentNum;
if(int.TryParse(num[i].ToString(),out currentNum)){
if(currentNum % 2 == 1){
summ += currentNum;
}
}
}
return summ;
}
}
The simplest and easiest way would be using loops to find sum of digits.
int sum = 0;
int n = 1234;
while(n > 0)
{
sum += n%10;
n /= 10;
}
#include <stdio.h>
int main (void) {
int sum = 0;
int n;
printf("Enter ir num ");
scanf("%i", &n);
while (n > 0) {
sum += n % 10;
n /= 10;
}
printf("Sum of digits is %i\n", sum);
return 0;
}
Surprised nobody considered the Substring method. Don't know whether its more efficient or not. For anyone who knows how to use this method, its quite intuitive for cases like this.
string number = "17463";
int sum = 0;
String singleDigit = "";
for (int i = 0; i < number.Length; i++)
{
singleDigit = number.Substring(i, 1);
sum = sum + int.Parse(singleDigit);
}
Console.WriteLine(sum);
Console.ReadLine();

Categories