c# newbie lost in recursive function [closed] - c#

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 9 years ago.
Improve this question
Hi I have problem with recursion in c#
Here is the code:
static int g(int a)
{
if (a > 0)
return -2 * g(a - 2) + 2;
else
return -2;
}
What is the result for:
Console.WriteLine(g(5));
Could some one explain me what is the value of int g when is not declared like int a ?

Could some one explain me what is the value of int g when is not
declared like int a ?
I don't understand what does the question mean, althought I'm going to explain you what does the function return if you pass 5.
Firstly lets declare another integer to make it easier:
static int g(int a)
{
if (a > 0){
int result = g(a - 2);
return -2 * result + 2;
}
else
return -2;
}
Then:
Console.WriteLine(g(5)) //-2*(-10)+2 = 22
if 5 > 0
result = g(3) //-2*(6)+2 = -10
return -2 * result + 2
if 3 > 0
result = g(1) //result = -2*(-2)+2 = 6
return -2 * result + 2
if 1 > 0
result = g(-1) //result = -2
return -2 * result + 2
if -1 < 0
return -2

You appear to lack an understanding of recursion. Let's simplify recursion to a "classic" base case which is much simpler than your example. Let's do a sum of from 1 to an input number:
public int SumAll(int number)
{
// Base case
if (number == 1)
{
return 1;
}
// Recursive call
return number + SumAll(number - 1);
}
Recursion always involves both calling a method within itself and a "base case" or termination step that stops the loop. In the above example, the "base case" is the number being equal to 1 to stop the loop.
The above example will evaluate as follows
return 5 + SumAll(4);
And SumAll(4) will evaluate as:
return 4 + SumAll(3);
Thus far, our final result will be:
5 + 4 + Sum(3);
And so forth... Study the method to understand why.

Related

C# Remove all preceding zeros from a double (no strings) [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 6 months ago.
This post was edited and submitted for review 6 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I need a method to return the firsts non zero numbers from a double in the following way: Any number >= 1 or == 0 will return the same; All the rest will return as per the following examples:
(Please note that I am using double because the potential imprecision is irrelevant in the use case whereas saving memory is relevant).
double NumberA = 123.2; // Returns 123.2
double NumberB = 1.2; // Returns 1.2
double NumberC = 0.000034; // Returns 3.4
double NumberD = 0.3; // Returns 3.0
double NumberE = -0.00000087; // Returns -8.7
One option would be to iteratively multiply by 10 until you get a number greater than 1:
public double RemoveLeadingZeros(double num)
{
if (num == 0) return 0;
while(Math.Abs(num) < 1) { num *= 10};
return num;
}
a more direct, but less intuitive, way using logarithms:
public double RemoveLeadingZeros(double num)
{
if (num == 0) return 0;
if (Math.Abs(num) < 1) {
double pow = Math.Floor(Math.Log10(num));
double scale = Math.Pow(10, -pow);
num = num * scale;
}
return num;
}
it's the same idea, but multiplying by a power of 10 rather then multiplying several times.
Note that double arithmetic is not always precise; you may end up with something like 3.40000000001 or 3.3999999999. If you want consistent decimal representation then you can use decimal instead, or string manipulation.
I would start with converting to a string. Something like this:
string doubleString = NumberC.ToString();
I don't know exactly what this will output, you will have to check. But if for example it is "0.000034" you can easily manipulate the string to meet your needs.

(num % 2) can result in 0, 1, and more? in C# [duplicate]

This question already has answers here:
Mod of negative number is melting my brain
(15 answers)
What is the difference between “int” and “uint” / “long” and “ulong”?
(6 answers)
How to detect a potential overflow
(1 answer)
Closed 3 years ago.
I'm solving some algorithm test which is Collatz conjecture.
In short,
1-1. if the number is even, divide it by 2
1-2. if odd, multiply it by 3 and plus 1
2. repeat the same process 1(1-1 or 1-2), until the number become 1.
For example,
6 become 1, after 8 tries(6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1).
In the test, it should be ended in 500 tries and returns times of try.
If it fails in 500 times, then returns -1.
Here's my code.
using System;
public class Program {
public int Main(int num) {
int answer = -1;
int maxTry = 500;
int count = 0;
if (num == 1)
return count;
for (count = 0; count < maxTry; count++)
{
// 1-1
if (num % 2 == 0)
{
num /= 2;
}
// 1-2
else
{
num = num * 3 + 1;
}
if (num == 1)
{
answer = count + 1;
break;
}
}
Console.Write(answer);
return answer;
}
}
It was working quite well, before meet '626331'!.
In explanation, 626331 can't be 1 in 500 times.
But with my code, it return 488, which means it becomes 1 at 488 tries.
When I printed process repeat by repeat, it looked working well.
After all attempts, found out that dividing was the problem.
I changed this
if (num % 2 == 0)
...
else
...
into
if (num % 2 == 0)
...
else if (num % 2 == 1)
...
Now every case works perfectly!
But I don't have any clue for this situation.
It was online coding test and compile option was C# Mono C# Compiler 5.14.0.177
You're getting overflow, and once overflowed the result will be negative and num % 2 can return 0 or -1. The % operator in C# is the remainder operator, not the mathematical modulo operator. See
Mod of negative number is melting my brain
You need to use a wider integer type (long) and enabling checked mode to detect overflow

Find Double/Float value is Odd or Even in C# [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 5 years ago.
Improve this question
How to find if double value is even or odd without converting them to int in C#? E.g.
123.0d - odd
456.0d - even
3.1415926d - floating point (neither odd nor even)
Try modulo % operator:
double x = 123;
string result = x % 2 == 0
? "even" : x % 2 == 1 || x % 2 == -1
? "odd"
: "floating point"; // e.g. 123.456789
Edit: When does it work? Floating point value (single, double) when it doesn't contain exponential part represents the (integer) value exactly.
https://en.wikipedia.org/wiki/Single-precision_floating-point_format
https://en.wikipedia.org/wiki/Double-precision_floating-point_format
So we have that the solution will work whenever x in these ranges
[-2**24..2**24] == [-16777216..16777216] (float)
[-2**52..2**52] == [-4503599627370496..4503599627370496] (double)
Please, notice, that since .Net assumes that negative % positive == nonpostive, e.g. -3 % 2 == -1 we have to check x % 2 == -1 as well as x % 2 == 1
well i think you answered your question by your own but here is a short code i wrote:
static void Main(string[] args)
{
double number=10.0;
if(number%2==0)
{
Console.WriteLine("Your number is even!");
}
else
{
Console.WriteLine("Your number is odd!");
}
Console.ReadLine();
}
this way you see really good if it works or not
public static bool IsEven(double x)
{
return x % 2 == 0;
}
Please note that it takes more code to make a helper method that does this than it does to actually do it, so if you ever put this in a production environment expect your QA team to send you nasty e-mails.
public bool isEven(double value)
{
decimal decVal = System.Convert.ToDecimal(value);
if (decVal % 2.0 == 0)
{
return true;
}
else
{
return false;
}
}
EDIT: if you convert to a decimal first it should work.

Algorithm: how many indivisible units are needed to overshadow a random number? [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 8 years ago.
Improve this question
How can I find how many indivisible units of 1,000 are needed to overshadow a random number?
For example, for random number 5,123 I'm going to need 6 x 1,000 to overshadow it, so: MyAlgorithm(5123, 1000) = 6
Edit1: I am sorry if despite my endeavor to articulate my problem into a meaningful description my dyslexia took over, I hope this edit makes it a bit more comprehensible.
Well, if I understand your question, it sounds like you could simply convert the parameters to decimals, divide, then use Math.Ceiling:
int output = (int)Math.Ceiling((decimal)5123 / (decimal)1000); // 6
Alternatively, you could avoid the conversions and rely purely on integer division and the % operator (modulus), like this:
int output = (5123 / 1000) + (5123 % 1000 == 0 ? 0 : 1);
If you want this in a method simply wrap it up like this:
static int MyAlgorithm(int a, int b)
{
return (a / b) + (a % b == 0 ? 0 : 1);
}
if I've understood you correctly, this is really just a one-liner:
public static int MyAlgorithm(int input, int units)
{
return input%units == 0 ? input/units : input/units + 1;
}
the only case when it isn't simply the result of input/units + 1 is the case when there is no remainder
public int MyAlgorithm(int x, int y)
{
int result = x / y;
return (result < 0) ? (result - 1): (result + 1);
}

Retrieving a value that is stored as MB [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 9 years ago.
Improve this question
I have a table that stores the amount of RAM a server has in a biginit column with values such as 2470208.
But how I can apply a data annotation or other validations to show only 2 instead of s470208. ?
I mean to always divide by 1 million and get the number on the left side of the digit ?
1) Use this for automatic thousands-unit:
string GetByteString(long n) {
int k=0;
string u=" kMGTEP";
while(n>1024) {
n>>=10;
k++;
}
return n.ToString() + u[k];
}
Call:
string s= GetByteString(1234567890123);
Debug.WriteLine(s);
2) But if you simply always want MB just shift by 20:
long n = 123456789;
string MB = (n>>20).ToString();
But this will show 0 if n goes below 1MB.
Reason:
1 kB = 2^10 = 1<<10 = 1024;
1 MB = 2^20 = 1<<20 = 1024*1024 = 1048576;
1 GB = 2^30 = 1<<30 = 1024*1024*1024 = 1073741824;
You tagged C# but mentioned a bigint column so it isn't clear whether you're looking for a database or C# solution. The following C# method will take the number of bytes as an integer and return a formatted string...
public string FormattedBytes(long bytes)
{
string units = " kMGT";
double logBase = Math.Log((double)bytes, 1024.0);
double floorBase = Math.Floor(logBase);
return String.Format("{0:N2}{1}b",
Math.Pow(1024.0, logBase - floorBase),
units.Substring((int)floorBase, 1));
}

Categories

Resources