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 1 year ago.
Improve this question
I am making a binary calc where you can enter a binary number and the program will output the dezimal number. The Script looks like this:
Binary Code Here
First I get the User input, then I reverse it because i will need to calc the numbers( 0 and 1s) backwards in the loop later on. Lets say I will input the Binary number 10 (2 in dezimal) in. First the loop will multiply 0 by 2 abd then multiply it by the power of 0. Then it will raise the "power multiplier" by 1. Now its going on again for 1 it will basicly do 1x2^1 again. At the end of the loop it always adds the calcutated summary to the var erg to output it later to the user. Somehow, as soon as i input something higher 1 it outputs the wrong calculated dezimal number. Is the variable type wrong or is the calculation wrong?
Just wanted to point out that .net can already do this conversion
int x = Convert.ToInt32(binaryString, 2); //base 2
When having a binary input you can obtain decimal result in one line with a help of Linq.
To convert binary, say, 111010 into decimal one can use loop with + and *:
111010 => ((((1 * 2 + 0) * 2 + 1) * 2 + 0) * 2 + 1) * 2 + 1
Code:
using System.Linq;
using System.Numerics;
...
BigInteger result = input.Aggregate(BigInteger.Zero, (s, a) => s * 2 + a - '0');
In case you prefer good old loop (no Linq solution):
BigInteger result = 0;
foreach(char c in input)
result = result * 2 + c - '0';
Fiddle
Related
My first idea was to make an array/list that has values assigned to each character.
So for example:
array[0] =' 0'
array[10] = 'A'
[...]
Then code would pick a random number y between [0,x] for slot 1.
For next slot [0,(x-y)] etc. When y <= 0 then fill rest of the slots with '0'.
Would that be enough for a simple voucher code generator? (It's not my decision to make encryption with this rule)
I am worried that sum of 9 is quite low for 6 character code, letters won't be used at all since they all have value over 9.
To prevent situation like this:
540000, 630000, 180000
Should I make chance of '0' to appear more?
What do you guys think about it?
Maybe you could also suggest some other way of doing this.
#Edit
Examples:
112320 = 1+1+2+3+2+0 = 9 Valid code, sum equals 9
000900 = 0+0+0+9+0+0 = 9 Valid code, sum equals 9
003015 = 0+0+3+0+1+5 = 9 Valid code, sum equals 9
A0012B = 10+0+0+1+2+11 = 24 Invalid code
Let's say that the function Rand(n) creates a random integer number that can go from 0 up to n (n included), then you can do the following:
Sum = 0;
A[0] = Rand(9);
Sum += A[0];
A[1] = Rand(9 - Sum);
Sum += A[1];
A[2] = Rand(9 - Sum);
Sum += A[2];
...
I just wrote this down very quickly, I didn't check the boundaries, but such an algorithm should do the trick.
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 want an solution to convert an input int say 010 to list of int {0,1,0}.
Below is code I tried, works until 0 is encountered.
Int num = 010;
List<int> listOfInt = new List<int>();
While(num > 0)
listOfInt.Add(num%10);
num / = 10;
I just want to split entered int and convert it to list of int. LINQ is fine if that could be efficient!
As others already mentioned 010 is identical to 10 when having parsed as int. However you could have your number as string coming from a console-input for example.
string myNumber = "010";
This can be split on every character quite easy using LINQ:
var intList = myNumber.Select(x => Convert.ToInt32(x.ToString())).ToList();
As every character is internally an int where '0' equals 49 you have to convert every single character to a string before which is done by using ToString.
Console.WriteLine("Enter a number:")
var input = Console.ReadLine();
List<int> result = input.Select(c => int.Parse(c.ToString())).ToList();
There is no difference between 010 and 10 either in computer arithmetic or real life. Zero is zero.
If you want to convert the number to a specific string format and extract the characters, perform the same steps as the statement:
10.ToString("000").Select(c=>c-48).ToList();
The result is a list with the numbers 0,1,0.
The expression c-48 takes advantage of the fact that characters are essentially ints, and digits start from 0 upwards. So 48 is 0, 1 is 49 etc.
If the input is a string, eg "10" you'll have to pad it with 0s up to the desired length:
"10".PadLeft(3,'0').Select(c=>c-48).ToList()
The result will be 0,1,0 again.
If, after all, you only want to retrieve characters from a paddes string, you only need padding, as a String is an IEnumerable. You can copy the characters to an array with String.ToCharArray() or to a List as before:
"10".PadLeft(3,'0').ToList()
string num = "010";
List<int> listOfInt = new List<int>();
foreach(char item in num)
{
listOfInt.Add(Convert.ToInt32(item.ToString()));
}
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 6 years ago.
Improve this question
I want to use as loop like : Example
i putted in textbox 123 and 300 in my formula.
1/2*(300+123/300) = 150.205 >> answer
i want to loop this Example i got answer 150.205 next formula should be look like this
1/2*(150.205+123/150.205) = 75.512
the answer of this equation i want to put in next formula by loop.
i have written code but i don't know how to use it via loop
My code.
double value = (0.5 * (300 + 123 / 300));
=======================================
For End loop
When condition match like this
1/2*(11.091+123/11.091) = 11.091
Meaning Answer and input where i m putting 300 will be same i want to break loop
**Example** I want to do this without using square root function in c#
like simple if i want a root of 9 it will be 3 so it will be like this .
i choosen 1 Because 9 is one value so i choosen 1
1/2*(1+9/1) = 5.000
1/2*(5+9/5) = 3.400
1/2*(3.4+9/3.4) = 3.024
1/2*(3.024+9/3.024) = 3.000
1/2*(3+9/3) = 3.000
see you will get same value in one point always
The only tricky thing here is a comparison with tolerance, since because of round up errors you can well never meet
answer == value
condition. The implementation could be
double answer = 300.0;
double tolerance = 1e-10;
while (true) {
// based on previous answer we compute next one
double value = 0.5 * (answer + 123.0 / answer);
//TODO: you can print out steps here, if you want something like this
//Console.WriteLine(value);
// check convergence with tolerance
if (Math.Abs(answer - value) <= tolerance) {
answer = value;
break;
}
// next answer (value) becomes the previous one (answer)
answer = value;
}
// 11.0905365064094
Console.Write(answer);
The actual answer (prove it) is just a square root:
// 11.09053650640941716205160010261...
Console.Write(Math.Sqrt(123));
Real life implementation (if my boss wants me to implement it):
public static double NewtonEstimation(Func<double, double> function,
double tolerance = 1e-10,
double guess = 1.0) {
if (null == function)
throw new ArgumentNullException("function");
else if (tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "tolerance must not be negative");
while (true) {
double value = function(guess);
if (Math.Abs(value - guess) <= tolerance)
return value;
guess = value;
}
}
...
// 11.0905365064094
Console.Write(NewtonEstimation(x => 0.5 * (x + 123 / x)));
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 9 years ago.
Improve this question
So I have this problem where I have to calculate the Fibonacci number of any given number from the user. I don't know how to do the actual calculations part, but everything else works. Here's my code. Can someone help me with the calculation part?
using System;
namespace Assignment
{
class MainClass
{
public static void Main (string[] args)
{
int sum = 0;
Console.WriteLine("Fibonacci Number: ");
String fib = Console.ReadLine ();
double result = Convert.ToDouble (fib);
for(int i = 0; i <= result; i++)
{
sum = i * i - 1;
}
Console.WriteLine ("!" + result + " = " + sum);
}
}
}
Extension on recursion approach - use anonymous recursion (which uses Fibonacci as example of recursive call):
Define recursive function: f(n+1) = f(n) + f(n-1);.
Grab definition of Y-Combinator from the article:
delegate Func<A,R> Recursive<A,R>(Recursive<A,R> r);
static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
{
Recursive<A, R> rec = r => a => f(r(r))(a);
return rec(rec);
}
Now use Y-combinator to construct recursive function:
Func<int,int> fib = Y<int,int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
Ready to call:
var fibOfSmallNumber = fib(4);
Now for large values you'd need BigInteger
Func<BigInteger,BigInteger> fibForBigNumbers =
Y<BigInteger,BigInteger>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
var fibOfBigNumber = fib(4);
Don't expect it to return value in short amount of time - default recursive implementation is very slow. Instead you should apply Memoization to remember previous values of the function (which also covered in the article).
Do you know the definition of the Fibonacci numbers? Please look them up; they have nothing to do with the polynomial x² - 1. The point of the problem is for you to translate the algorithm into C♯.
There are three general approaches you'll find:
Iteration by a for loop.
Recursion.
Direct formulas using exponentiation.
Try it all three ways. I suggest you look at the textbook by Graham, Knuth, and Patashnik, Concrete Mathematics. You'll learn some of the history too.
If what you want is the nth fibonacci number something like this should work:
const double goldenratio = 1.6180339887;
int n = 16;
int nthfib = Math.Round(Math.Pow(goldenratio, n - 1) / Math.Sqrt(5));
nthfib will equal the 16th fibonacci number, 610.
Since the fibonacci sequence gets very large rather quickly, you might need a limit set on n so that nthfib doesn't max out.
I did a math problem today and first attempted it in Python but after getting the wrong answer I used C#. Basically I was to add up all the digits a long number (2^1000). The sum of these digits was the answer. Here is my python script:
#! /usr/bin/env python3
n = 2**1000
count = 0
while (n > 0):
count += n % 10
n = (int)(n/10)
print (count)
This script gives the result 1189. Essentially I'm adding the last digit of the number to count, then removing it from the number and repeating the process. Here is similar code in C#:
//Yes this string is the same output from 2^1000. I had python write the string to file for me.
String str = "10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376";
Int32 answer = 0;
foreach (char c in str)
{
answer += (Convert.ToInt32(c) - 48);
}
lblOutput.Text = answer.ToString();
C# gives the output: 1366 which is the correct answer. I'm just curious as to why my python script gets the wrong answer. Am I looking at the math in the wrong way?
Just do this:
n = 2 ** 1000
count = 0
while n > 0:
count += n % 10
n //= 10
print(count)
Why your code goes wrong is because (int)(n/10) first converts n to a double, divides it by 10 and then truncates. Rounding errors are easily made in this process. In Python 3.X // is used for integer division.
Oh and finally, (int)(n / 10) is a very bad style, we don't use C-style casts in Python. You create a int() object, so you use int(n / 10). This is error prone thanks to rounding errors, so use integer division instead: n // 10. And since we are doing n = n // 10 we can write n //= 10.
Use integer division.
n = n//10
By truncating after, you're losing very large fractions of 1 many times.
I know that this question is really old but after reading over it I couldn't seem to understand the code and felt it was too hard for beginners to understand so I made a more 'noob-friendly' version using a list:
n=2**1000
thelist=list(map(int, str(n)))
counter=0
for x in range(0,len(thelist)):
counter+=thelist[x]
print(counter)
(i understand that this is less efficient btw)