C# Object method in separate is not picking up in Main - c#

class Rational
{
private int Denominator, Numerator;
public Rational(int numerator = 0, int denominator = 1)
{
Numerator = numerator;
Denominator = denominator;
}
public override string ToString()
{
return string.Format("Fraction: {0} / {1}", Numerator, Denominator);
}
public void IncreaseBy(Rational other)
{
Numerator = other.Numerator + Numerator;
Denominator = other.Denominator + Denominator;
}
public void DecreaseBy(Rational other)
{
Numerator = Numerator - other.Numerator;
Denominator = Denominator - other.Denominator;
}
}
This class is a simple one. It is suppose to add or substract a denominator and numerator in my main.
This is in the main, bother under the same namespace
It is suppose to ask the user for the denominator and numerator 4 times. and add them both by 3
class Program
{
static void Main(string[] args)
{
int i = 0;
Console.WriteLine("Print 4 rational numbers.\n");
do
{
Console.Write("Choose a numberator: ");
int myNumerator = Convert.ToInt32(Console.ReadLine());
Console.Write("Choose a denominator: ");
int myDenominator = Convert.ToInt32(Console.ReadLine());
Rational original = new Rational(myNumerator, myDenominator);
original.IncreaseBy(3, 3);
Console.WriteLine(original);
i++;
} while (i < 4);
}

The IncreaseBy method takes one argument, you are giving it two. You need to give it one Rational, so...
original.IncreaseBy(new Rational(3, 3));

Related

How to convert a growing recursive math function to code?

static void Main(string[] args)
{
var k0 = Convert.ToInt32(Console.ReadLine());
var kn = Convert.ToInt32(Console.ReadLine());
var result = Calculate(k0, kn);
}
private static double Calculate(int k0, int kn)
{
var k1 = Math.Round(Math.Pow(Math.Sqrt(k0) + Math.Sqrt(Math.PI), 2)); // first iteration
var k2 = Math.Round(Math.Pow(Math.Sqrt(k1) + Math.Sqrt(Math.PI), 2)); // 2nd iteration
var k3 = Math.Round(Math.Pow(Math.Sqrt(k2) + Math.Sqrt(Math.PI), 2)); // 3rd iteration
// calculate until kn
return k3; // this should return kn
}
How should I change this code so it can recursively calculate until kn'th iteration?
To avoid confusion, I don't think you're asking about recursive functions/methods that call themselves until some desired condition and then return a value.
This is easy enough using a for loop
private static double Calculate(int k0, int kn)
{
double result = k0;
for (var i = 0; i < kn; i++){
result = Math.Round(Math.Pow(Math.Sqrt(result) + Math.Sqrt(Math.PI), 2));
}
return result;
}
You could do this with recursion but in this case that would be overkill and it's not necessary.
Recursive which has the same signature, since you asked for it
private static double Calculate(int k, int n)
{
return n == 0 ? k : Math.Round(Math.Pow(Math.Sqrt(Calculate(k, n - 1)) + Math.Sqrt(Math.PI), 2));
}
If you want a recursive solution:
private static double Calculate(int k0, int kn)
{
return CalculateInternal(k0, kn, 1);
}
private static double CalculateInternal(int ki, int kn, int n)
{
// Base case: exit when we've completed all iterations
if (n > kn) return ki;
// Current iteration
var x = Math.Round(Math.Pow(Math.Sqrt(ki) + Math.Sqrt(Math.PI), 2));
// Pass current iteration to next iteration
return CalculateInternal(x, kn, n + 1);
}
Well you could try to do this by adding in an optional argument.
private static double Calculate(int k0, int kn, int i = 0)
{
if(i < kn)
{
return Calculate( Math.Round(Math.Pow(Math.Sqrt(k0) + Math.Sqrt(Math.PI), 2)) , kn, ++i);
}
return k0;
}

Adding and subtracting vulgar fractions

I'm trying to add two vulgar fractions together by finding the lowest common denominator and then adding. However, my code isn't behaving as expected, and is outputting two very high negative numbers. When I change the second fraction to 3/15 it outputs 0/0.
Here is my main program code:
class Program
{
static void Main(string[] args)
{
Fraction n = new Fraction(2, 4);
Fraction z = new Fraction(3, 12);
Fraction sum = n.Add(z, n);
int num = sum.Numerator;
int den = sum.Denominator;
Console.WriteLine("{0}/{1}", num, den);
Console.ReadKey(true);
}
}
Here is my Fraction class code:
internal class Fraction
{
public Fraction(int numerator, int denominator)
{
Numerator = numerator;
Denominator = denominator;
}
public int Numerator { get; private set; }
public int Denominator { get; private set; }
public Fraction Add(Fraction fraction2, Fraction fraction8)
{
int lcd = GetLCD(fraction8, fraction2);
int x = lcd/fraction8.Denominator;
int n = lcd/fraction2.Denominator;
int f2num = fraction2.Numerator*n;
int f8num = fraction8.Numerator*x;
int t = fraction2.Numerator;
Fraction Fraction3 = new Fraction(f2num+f8num,lcd);
return Fraction3;
}
public int GetLCD(Fraction b, Fraction c)
{
int i = b.Denominator;
int j = c.Denominator;
while (true)
{
if (i == j)
{
return i;
}
j = j + j;
i = i + i;
}
}
}
It didn't make sense to have GetLCD, Add & Subtract methods in the class. So, I moved it out of the class and made them static methods.
Your GetLCD function doesn't get LCD correctly. This will give you the required result.(I didn't bother to make the Subtract method working, you can follow the below code & make it work yourself)
PS: I didn't change all of your variable names & I would recommend you to make them as meaningful as possible. n,z,x,y,b,c are not good variable names
static void Main(string[] args)
{
Fraction n = new Fraction(2, 4);
Fraction z = new Fraction(3, 12);
Fraction sum = Add(z, n);
int x = sum.Numerator;
int y = sum.Denominator;
Console.WriteLine("{0}/{1}", x, y);
Console.ReadKey(true);
}
public static Fraction Add(Fraction fraction2, Fraction fraction8)
{
int lcd = GetLCD(fraction8, fraction2);
int multiplier = 0;
if (fraction2.Denominator < lcd)
{
multiplier = lcd / fraction2.Denominator;
fraction2.Numerator = multiplier * (fraction2.Numerator);
fraction2.Denominator = multiplier * (fraction2.Denominator);
}
else
{
multiplier = lcd / fraction8.Denominator;
fraction8.Numerator = multiplier * (fraction8.Numerator);
fraction8.Denominator = multiplier * (fraction8.Denominator);
}
Fraction Fraction3 = new Fraction(fraction2.Numerator + fraction8.Numerator, lcd);
return Fraction3;
}
public static int GetLCD(Fraction b, Fraction c)
{
int i = b.Denominator;
int j = c.Denominator;
int greater = 0;
int lesser = 0;
if (i > j)
{
greater = i; lesser = j;
}
else if (i < j)
{
greater = j; lesser = i;
}
else
{
return i;
}
for (int iterator = 1; iterator <= lesser; iterator++)
{
if ((greater * iterator) % lesser == 0)
{
return iterator * greater;
}
}
return 0;
}
internal class Fraction
{
public Fraction(int numerator, int denominator)
{
Numerator = numerator;
Denominator = denominator;
}
public int Numerator { get; set; }
public int Denominator { get; set; }
}
Personally, I think your first mistake is trying to calculate the Lowest Common Denominator instead of just finding the simplest common denominator. Finding the LCD is a great stratgety for humans working this out on paper because of pattern recognition: we can recognize LCDs quickly; but calculating the LCD, and then converting the fractions to it is significantly more steps for a computer that must perform every step every time (and is not able to recognize patterns). Plus, once you add the two fractions after transforming them to their LCD it isn't even guaranteed to be a reduced result. I'm assuming that the reduced result is required, as is usually expected with fractional arithmetic. And because it seems useful, I put the reduction directly into the constructor code:
internal class Fraction
{
public Fraction(int numerator, int denominator, bool reduce = false)
{
if (!reduce)
{
Numerator = numerator;
Denominator = denominator;
}
else
{
var GCD = GreatestCommonDivisor(numerator, denominator);
Numerator = numerator / GCD;
Denominator = denominator / GCD;
}
}
public int Numerator { get; private set; }
public int Denominator { get; private set; }
public static Fraction Add(Fraction first, Fraction second)
{
return Combine(first, second, false);
}
public static Fraction Subtract(Fraction first, Fraction second)
{
return Combine(first, second, true);
}
private static Fraction Combine(Fraction first, Fraction second, bool isSubtract)
{
var newDenominator = first.Denominator * second.Denominator;
var newFirst = first.Numerator * second.Denominator;
var newSecond = first.Denominator * second.Denominator;
if (isSubtract)
{
newSecond = newSecond * -1;
}
return new Fraction(newFirst + newSecond, newDenominator, true);
}
private static int GreatestCommonDivisor(int a, int b)
{
return b == 0 ? a : GreatestCommonDivisor(b, a % b);
}
}
Edit: stole Greatest Common Divisor code from this answer

Find the number

This is a problem statement.
Consider a number 2345. If you multiply its digits then you get the number 120. Now if you again multiply digits of 120 then you will get number 0 which is a one digit number. If I add digits of 2345 then I will get 14. If I add digits of 14 then I will get 5 which is a one digit number.
Thus any number can be converted into two one digit numbers in some number of steps. You can see 2345 is converted to 0 by using multiplication of digits in 2 steps and it is converted to 5 by using addition of digits in 2 steps. Now consider any number N. Let us say that it can be converted by multiplying digits to a one digit number d1 in n1 steps and by adding digits to one digit number d2 in n2 steps.
Your task is to find smallest number greater than N and less than 1000000000 which can be converted by multiplying its digits to d1 in less than or equal to n1 steps and by adding its digits to d2 in less than or equal to n2 steps.
How to solve it in C#...
I think you're simply approaching / interpreting the problem incorrectly; here's a stab in the dark:
using System;
using System.Diagnostics;
static class Program
{
static void Main()
{
// check our math first!
// You can see 2345 is converted to 0 by using multiplication of digits in 2 steps
int value, steps;
value = MultiplyToOneDigit(2345, out steps);
Debug.Assert(value == 0);
Debug.Assert(steps == 2);
// and it is converted to 5 by using addition of digits in 2 steps
value = SumToOneDigit(2345, out steps);
Debug.Assert(value == 5);
Debug.Assert(steps == 2);
// this bit is any random number
var rand = new Random();
for (int i = 0; i < 10; i++)
{
int N = rand.Next(0, MAX);
int result = Execute(N);
Console.WriteLine("For N={0}, our answer is {1}", N, result);
}
}
const int MAX = 1000000000;
//Now consider any number N.
static int Execute(int N)
{
// Let us say that it can be converted by multiplying digits to a one digit number d1 in n1
// steps and by adding digits to one digit number d2 in n2 steps.
int n1, n2;
int d1 = MultiplyToOneDigit(N, out n1),
d2 = SumToOneDigit(N, out n2);
// Your task is to find smallest number greater than N and less than 1000000000
for (int i = N + 1; i < MAX; i++)
{
int value, steps;
// which can be converted by multiplying its digits to d1 in less than or equal to n1 steps
value = MultiplyToOneDigit(i, out steps);
if (value != d1 || steps > n1) continue; // no good
// and by adding its digits to d2 in less than or equal to n2 steps.
value = SumToOneDigit(i, out steps);
if(value != d2 || steps > n2) continue; // no good
return i;
}
return -1; // no answer
}
static int MultiplyToOneDigit(int value, out int steps)
{
steps = 0;
while (value > 10)
{
value = MultiplyDigits(value);
steps++;
}
return value;
}
static int SumToOneDigit(int value, out int steps)
{
steps = 0;
while (value > 10)
{
value = SumDigits(value);
steps++;
}
return value;
}
static int MultiplyDigits(int value)
{
int acc = 1;
while (value > 0)
{
acc *= value % 10;
value /= 10;
}
return acc;
}
static int SumDigits(int value)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
return total;
}
}
There are two memory problems I can see; the first is the generation of lots of strings - you might want to approach that something like:
static int SumDigits(int value)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
return total;
}
(which is completely untested)
The second problem is the huge list; you don't need to store (in lstString) every value just to find a minimum. Just keep track of the best you've done so far. Or if you need the data for every value, then: don't store them as a string. Indeed, the i can be implied anyway (from the position in the list/array), so all you would really need would be an int[] of the cnt values for every value. And int[1000000000] is 4GB just by itself, so would require the large-array support in recent .NET versions (<gcAllowVeryLargeObjects>). But much better would be: just don't store it.
But it's throwing System.OutOfMemoryException .
That simply mean you're running out of memory. Your limit is 1,000,000,000 or roughly 1G. Times 4 bytes for a string reference that's already too large for a 32 bit system. Even without the actual strings.
You can store your answers more compactly in an int[] array but that would still show the same problem.
So, lower your limit or compile and run on a 64 bit PC.
A for effort :)
Now doing together. You can of course do refactoring.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _17082903_smallest_greatest_number
{
class Program
{
static void Main(string[] args)
{
int N = 2344;
int n1 = 0;
int n2 = 0;
int d1 = SumDigits(N, ref n1);
int d2 = ProductDigits(N, ref n2);
bool sumFound = false, productFound = false;
for (int i = N + 1; i < 1000000000; i++)
{
if (!sumFound)
{
int stepsForSum = 0;
var res = SumDigits(i, ref stepsForSum);
if (res == d1 && stepsForSum <= n1)
{
Console.WriteLine("the smallest number for sum is: " + i);
Console.WriteLine(string.Format("sum result is {0} in {1} steps only", res, stepsForSum));
sumFound = true;
}
stepsForSum = 0;
}
if (!productFound)
{
int stepsForProduct = 0;
var res2 = ProductDigits(i, ref stepsForProduct);
if (res2 == d2 && stepsForProduct <= n2)
{
Console.WriteLine("the smallest number for product is: " + i);
Console.WriteLine(string.Format("product result is {0} in {1} steps only", res2, stepsForProduct));
productFound = true;
}
stepsForProduct = 0;
}
if (productFound && sumFound)
{
break;
}
}
}
static int SumDigits(int value, ref int numOfSteps)
{
int total = 0;
while (value > 0)
{
total += value % 10;
value /= 10;
}
numOfSteps++;
if (total < 10)
{
return total;
}
else
{
return SumDigits(total, ref numOfSteps);
}
}
static int ProductDigits(int value, ref int numOfSteps)
{
int total = 1;
while (value > 0)
{
total *= value % 10;
value /= 10;
}
numOfSteps++;
if (total < 10)
{
return total;
}
else
{
return ProductDigits(total, ref numOfSteps);
}
}
}
}

How to simplify fractions?

How to simplify a fraction in C#? For example, given 1 11/6, I need it simplified to 2 5/6.
If all you want is to turn your fraction into a mixed number whose fractional part is a proper fraction like the previous answers assumed, you only need to add numerator / denominator to the whole part of the number and set the numerator to numerator % denominator. Using loops for this is completely unnecessary.
However the term "simplify" usually refers to reducing a fraction to its lowest terms. Your example does not make clear whether you want that as well, as the example is in its lowest terms either way.
Here's a C# class that normalizes a mixed number, such that each number has exactly one representation: The fractional part is always proper and always in its lowest terms, the denominator is always positive and the sign of the whole part is always the same as the sign of the numerator.
using System;
public class MixedNumber {
public MixedNumber(int wholePart, int num, int denom)
{
WholePart = wholePart;
Numerator = num;
Denominator = denom;
Normalize();
}
public int WholePart { get; private set; }
public int Numerator { get; private set; }
public int Denominator { get; private set; }
private int GCD(int a, int b)
{
while(b != 0)
{
int t = b;
b = a % b;
a = t;
}
return a;
}
private void Reduce(int x) {
Numerator /= x;
Denominator /= x;
}
private void Normalize() {
// Add the whole part to the fraction so that we don't have to check its sign later
Numerator += WholePart * Denominator;
// Reduce the fraction to be in lowest terms
Reduce(GCD(Numerator, Denominator));
// Make it so that the denominator is always positive
Reduce(Math.Sign(Denominator));
// Turn num/denom into a proper fraction and add to wholePart appropriately
WholePart = Numerator / Denominator;
Numerator %= Denominator;
}
override public String ToString() {
return String.Format("{0} {1}/{2}", WholePart, Numerator, Denominator);
}
}
Sample usage:
csharp> new MixedNumber(1,11,6);
2 5/6
csharp> new MixedNumber(1,10,6);
2 2/3
csharp> new MixedNumber(-2,10,6);
0 -1/3
csharp> new MixedNumber(-1,-10,6);
-2 -2/3
int unit = 1;
int numerator = 11;
int denominator = 6;
while(numerator >= denominator)
{
numerator -= denominator;
if(unit < 0)
unit--;
else
unit++;
}
Then do whatever you like with the variables.
Note that this isn't particularly general.... in particular I doubt it's going to play well with negative numbers (edit: might be better now)
int num = 11;
int denom = 6;
int unit = 1;
while (num >= denom)
{
num -= denom;
unit++;
}
Sorry I didn't fully understand that part about keeping track of the unit values.
to simplify the fraction 6/11 you would see if you could get both to line up by the same number greater than 1 and divide.
So
2,4,6,8,10,12 no
1,3,6,9,12 no
4,8 no
5,10 no
6,12 no
7 no
8 no
9 no.
No will be the answer for all so it is already in simplest. There is no more to be done.

round up given number in c#

I want round up given numbers in c#
Ex:
round(25)=50
round(250) = 500
round(725) = 1000
round(1200) = 1500
round(7125) = 7500
round(8550) = 9000
Most of your data suggests that you want to round up to the nearest multiple of 500. This would be done by
int round(int input)
{
return (int)(500 * Math.Ceiling(input / 500.0));
}
The rounding of 25 to 50 will not work, though.
Another guess would be that you want your rounding to depend on the size of the number being rounded. The following function would round 25 to 50, 250 to 500, 0.025 to 0.05, and 2500 to 5000. Maybe you can work from there.
double round(double input)
{
double scale = Math.Floor(Math.Log10(input));
double step = 5 * Math.Pow(10, scale);
return step * Math.Ceiling(input/step);
}
Depending on what you need, this could be a nice, reusable solution.
static int RoundUpWeird(int rawNr)
{
if (rawNr < 100 && rawNr > -100)
return RoundUpToNext50(rawNr);
else
return RoundUpToNext500(rawNr);
}
static int RoundUpToNext50(int rawNr)
{
return RoundUpToNext(rawNr, 50);
}
static int RoundUpToNext500(int rawNr)
{
return RoundUpToNext(rawNr, 500);
}
static int RoundUpToNext(int rawNr, int next)
{
int result;
int remainder;
if ((remainder = rawNr % next) != 0)
{
if (rawNr >= 0)
result = RoundPositiveToNext(rawNr, next, remainder);
else
result = RoundNegativeToNext(rawNr, remainder);
if (result < rawNr)
throw new OverflowException("round(Number) > Int.MaxValue!");
return result;
}
return rawNr;
}
private static int RoundNegativeToNext(int rawNr, int remainder)
{
return rawNr - remainder;
}
private static int RoundPositiveToNext(int rawNr, int next, int remainder)
{
return rawNr + next - remainder;
}
This code should work according to the rules I can gather:
public static double Round(double val)
{
int baseNum = val <= 100 ? 100 : 1000;
double factor = 0.5;
double v = val / baseNum;
var res = Math.Ceiling(v / factor) / (1 / factor) * baseNum;
return res;
}
This should work. And also for numbers greater than those you wrote:
int round(int value)
{
int i = 1;
while (value > i)
{
i *= 10;
}
return (int)(0.05 * i * Math.Ceiling(value / (0.05 * i)));
}

Categories

Resources