Compute for the summation of X^2 - c#

Given x = 3;
I need to compute for the summation of the value of x = 3 + 2 + 1
x = 6;
int input = 3;
int retVal = 0;
for (int i = 0; i <= input; i++)
{
retVal += i;
}
Console.WriteLine(retVal);
I was able to compute for the summation of x.
How can i compute for the value of summation of x^2
for example
x x^2
1 1
2 4
3 9
summation of x = 6
summation of x^2 = 14
I have tried the following code
int input = 3;
int retVal = 0;
int summation = input * input;
for (int i = 0; i <= input; i++)
{
retVal += i;
summation += i;
}
Console.WriteLine(retVal);
Console.WriteLine(summation);

Let me explain you your code:
int input = 3;
int retVal = 0;
int summation = input * input; //summation is equal to 9
for (int i = 0; i <= input; i++)
{
retVal += i;
summation += i; /*this is basically saying add summation plus i
tosummation (9 is assigned 9 + 0 so summation is still 9). Then, when i is 1,
summation changes to 10. When i is 2, summation changes to 12, and when i is 3,
summation is 15. What you should be doing is initialize summation to 0 and in
the for loop, do this: summation += i * i (summation is assigned summation + (i * i)) Also, no need to start i from 0 (it is doing one extra loop for nothing). You should start i from 1. */
}
Console.WriteLine(retVal);
Console.WriteLine(summation); //Another user already provided the solution. I just wanted to explain you your code.

int input = 3;
int retVal = 0;
int summation = 0; //<=Chnaged from input * input
for (int i = 1; i <= input; i++) //<=Changed from 0 to 1
{
retVal += i;
summation += i * i; //<= changed from i
}
Console.WriteLine(retVal);
Console.WriteLine(summation);

You need to take power of value before adding by using Math.Pow
var input = 3;
var summation = 0;
var power = 2;
for (int i = 1; i <= input; i++) //initialize i = 1 because first entry is 1 don't start it from 0
{
summation += (int)Math.Pow(i, power);
}
Console.WriteLine(summation);

You can use Enumerable.Range() to achieve this.
public static int Summation(int count, Func<int, int> series)
{
return Enumerable.Range(1, count).Select(series).Sum();
}
Example of use - Summation(3, x => x * x) would return 14.

Related

Factorials of Big numbers without BigInteger (C#)

Is there an algorithm for calculating a factorial without using System.Numerics library? We receive an int number and we need to return factorial of this number as string(if n = 30, we should return "265252859812191058636308480000000", if n = 70, we should return "11978571669969891796072783721689098736458938142546425857555362864628009582789845319680000000000000000" ect. Numbers are very big)
I tried to find out, did anyone already write an article about that, but I didn't find anything.
It suffices to implement multiplication of a large number as a string by a small integer.
Illustration: 12! = 11! x 12 is obtained by multiplying every digit by 12 and summing (with shifts):
39916800
36
108
108
12
72
96
0
0
---------
479001600
A lazy solution. It is possible to evaluate the factorial with just BigNum addition, replacing the multiplications by successive additions. (For n!, we will perform 1+2+3+...n-1 additions. This is acceptable for moderate n.)
The computation uses two pre-allocated string (arrays of char), which are initially filled with null bytes (Writeline skips them). When adding from right to left, we stop when we meet a null.
int n = 20;
// Factorial and temporary string; 100! fits in 158 digits
const int N = 158;
char[] f = new char[N], t = new char[N];
f[N - 1] = '1'; // 1!
// Product up to n by successive additions
for (int i = 2; i <= n; i++)
{
// t= f
f.CopyTo(t, 0);
for (int j = 0; j < i - 1; j++)
{
// f+= t, repeated i-1 times
int c = 0; // Carry
for (int k = N - 1; k >= 0; k--)
{
if (t[k] == 0 && c == 0) break; // Significant part exhausted
int d = Math.Max(0, t[k] - '0') + Math.Max(0, f[k] - '0') + c;
c= d / 10; d = d % 10; f[k] = (char)(d + '0'); // Next carry/digit
}
}
Console.WriteLine(f);
}
Output:
2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
6227020800
87178291200
1307674368000
20922789888000
355687428096000
6402373705728000
121645100408832000
2432902008176640000
static string FindFactorial(int n)
{
int[] result = new int[500000];
result[0] = 1;
int resultSize = 1;
for (int x = 2; x <= n; x++)
resultSize = Multiply(x, result, resultSize);
string factorial = "";
for (int i = resultSize - 1; i >= 0; i--)
factorial += result[i].ToString();
return factorial;
}
static int Multiply(int x, int[] result, int resultSize)
{
int carry = 0;
for (int i = 0; i < resultSize; i++)
{
int product = result[i] * x + carry;
result[i] = product % 10;
carry = product / 10;
}
while (carry != 0)
{
result[resultSize] = carry % 10;
carry /= 10;
resultSize++;
}
return resultSize;
}
This will work

Multiply two column datagridview cell values for another column then sum values of all rows

I have this datagridview where I sum all time under tension value with this code:
int finalSum = 0;
for (int p = 0; p < dataGridView1.Rows.Count; ++p)
{
finalSum += getCellDigitSum(Convert.ToInt32(dataGridView1.Rows[p].Cells[4].Value));
}
label22.Text = finalSum.ToString();
int getCellDigitSum(int cellValue)
{
int l = cellValue;
int result = 0;
while (l > 0)
{
result += (l % 10);
l = l / 10;
}
return result;
}
With this code I obtain the sum of single values (201 become 3) and then the sum of all rows.
The problem is that I need to first multiply the "Serie" column value for the "Ripetizioni" value, then multiply the result for the sum of multiple digits "time under tension" (201 will be 3) and at the end multiply the result for all the rows.
This is the datagridview
So for example in the first row I need to do 11 x 3 = result x (201 sum so 3).
Loop for all the rows and do the sum of values
Please try this. let me know incase you face any issue. Calculation can be modified according to requirement.
int finalSum = 0;
for (int p = 0; p < dataGridView1.Rows.Count; ++p)
{
finalSum += getCellDigitSum(dataGridView1.Rows[p]);
}
//label22.Text = finalSum.ToString();
int getCellDigitSum(DataGridViewRow dr)
{
int serie = Convert.ToInt32(dr.Cells[0].Value);//you can change cell index or use column name
int ripetizioni = Convert.ToInt32(dr.Cells[1].Value);//you can change cell index or use column name
//timeundertension
int l = Convert.ToInt32(dr.Cells[3].Value);
int sumTimeUnderTension = 0;
int result = 0;
while (l > 0)
{
sumTimeUnderTension += (l % 10);
l = l / 10;
}
result = serie * ripetizioni * sumTimeUnderTension;
return result;
}

Reorder digits in integer using C#

I want to ask how I can reorder the digits in an Int32 so they result in the biggest possible number.
Here is an example which visualizes what I am trying to do:
2927466 -> 9766422
12492771 -> 97742211
I want to perform the ordering of the digits without using the System.Linq namespace and without converting the integer into a string value.
This is what I got so far:
public static int ReorderInt32Digits(int v)
{
int n = Math.Abs(v);
int l = ((int)Math.Log10(n > 0 ? n : 1)) + 1;
int[] d = new int[l];
for (int i = 0; i < l; i++)
{
d[(l - i) - 1] = n % 10;
n /= 10;
}
if (v < 0)
d[0] *= -1;
Array.Sort(d);
Array.Reverse(d);
int h = 0;
for (int i = 0; i < d.Length; i++)
{
int index = d.Length - i - 1;
h += ((int)Math.Pow(10, index)) * d[i];
}
return h;
}
This algorithm works flawlessly but I think it is not very efficient.
I would like to know if there is a way to do the same thing more efficiently and how I could improve my algorithm.
You can use this code:
var digit = 2927466;
String.Join("", digit.ToString().ToCharArray().OrderBy(x => x));
Or
var res = String.Join("", digit.ToString().ToCharArray().OrderByDescending(x => x) );
Not that my answer may or may not be more "efficient", but when I read your code you calculated how many digits there are in your number so you can determine how large to make your array, and then you calculated how to turn your array back into a sorted integer.
It would seem to me that you would want to write your own code that did the sorting part without using built in functionality, which is what my sample does. Plus, I've added the ability to sort in ascending or descending order, which is easy to add in your code too.
UPDATED
The original algorithm sorted the digits, now it sorts the digits so that the end result is the largest or smallest depending on the second parameter passed in. However, when dealing with a negative number the second parameter is treated as opposite.
using System;
public class Program
{
public static void Main()
{
int number1 = 2927466;
int number2 = 12492771;
int number3 = -39284925;
Console.WriteLine(OrderDigits(number1, false));
Console.WriteLine(OrderDigits(number2, true));
Console.WriteLine(OrderDigits(number3, false));
}
private static int OrderDigits(int number, bool asc)
{
// Extract each digit into an array
int[] digits = new int[(int)Math.Floor(Math.Log10(Math.Abs(number)) + 1)];
for (int i = 0; i < digits.Length; i++)
{
digits[i] = number % 10;
number /= 10;
}
// Order the digits
for (int i = 0; i < digits.Length; i++)
{
for (int j = i + 1; j < digits.Length; j++)
{
if ((!asc && digits[j] > digits[i]) ||
(asc && digits[j] < digits[i]))
{
int temp = digits[i];
digits[i] = digits[j];
digits[j] = temp;
}
}
}
// Turn the array of digits back into an integer
int result = 0;
for (int i = digits.Length - 1; i >= 0; i--)
{
result += digits[i] * (int)Math.Pow(10, digits.Length - 1 - i);
}
return result;
}
}
Results:
9766422
11224779
-22345899
See working example here... https://dotnetfiddle.net/RWA4XV
public static int ReorderInt32Digits(int v)
{
var nums = Math.Abs(v).ToString().ToCharArray();
Array.Sort(nums);
bool neg = (v < 0);
if(!neg)
{
Array.Reverse(nums);
}
return int.Parse(new string(nums)) * (neg ? -1 : 1);
}
This code fragment below extracts the digits from variable v. You can modify it to store the digits in an array and sort/reverse.
int v = 2345;
while (v > 0) {
int digit = v % 10;
v = v / 10;
Console.WriteLine(digit);
}
You can use similar logic to reconstruct the number from (sorted) digits: Multiply by 10 and add next digit.
I'm posting this second answer because I think I got the most efficient algorithm of all (thanks for the help Atul) :)
void Main()
{
Console.WriteLine (ReorderInt32Digits2(2927466));
Console.WriteLine (ReorderInt32Digits2(12492771));
Console.WriteLine (ReorderInt32Digits2(-1024));
}
public static int ReorderInt32Digits2(int v)
{
bool neg = (v < 0);
int mult = neg ? -1 : 1;
int result = 0;
var counts = GetDigitCounts(v);
for (int i = 0; i < 10; i++)
{
int idx = neg ? 9 - i : i;
for (int j = 0; j < counts[idx]; j++)
{
result += idx * mult;
mult *= 10;
}
}
return result;
}
// From Atul Sikaria's answer
public static int[] GetDigitCounts(int n)
{
int v = Math.Abs(n);
var result = new int[10];
while (v > 0) {
int digit = v % 10;
v = v / 10;
result[digit]++;
}
return result;
}

Creating 2 numbers from a one #C

I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.
int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;
while (checkCount > 0)
{
if (checkCount % 2 == 0)
count2++;
else
countRest++;
checkCount /= 10;
}
int[] a = new int[count2];
int[] b = new int[countRest];
int k2 = 0, kRest = 0;
for (int j = 0; j < a.Length + b.Length; j++)
{
if (num1 % 2 == 0)
{
a[k2] = num1 % 10;
k2++;
}
else
{
b[kRest] = num1 % 10;
kRest++;
}
num1 /= 10;
}
I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?
Example:
If I have this number - 12345 so
var = 24, other var = 135
If you have another solution without arrays I think it will be better.
Thank you.
Why not just:
int decimalMaskA = 1;
int decimalMaskB = 1;
while (checkCount > 0)
{
if (checkCount % 2 == 0)
{
count2 = count2 + (checkCount % 10)*decimalMaskA;
decimalMaskA *= 10;
}
else
{
countRest = countRest + (checkCount % 10)*decimalMaskB;
decimalMaskB *= 10;
}
checkCount /= 10;
}
count2 and countRest will contain those numbers (135 and 24) instead of counts.
This splits number 12345 to numbers 135 and 24.
int checkCount = 12345;
int even = 0;
int odd = 0;
int reverseEven = 0;
int reverseOdd = 0;
while (checkCount > 0) {
int current = checkCount % 10;
if (current % 2 == 0) {
reverseEven = 10 * reverseEven + current;
} else {
reverseOdd = 10 * reverseOdd + current;
}
checkCount /= 10;
}
while (reverseEven > 0) {
even = 10 * even + reverseEven % 10;
reverseEven /= 10;
}
while (reverseOdd > 0) {
odd = 10 * odd + reverseOdd % 10;
reverseOdd /= 10;
}
Console.WriteLine("even: {0}", even);
Console.WriteLine("odd: {0}", odd);
If I understand what you're looking for this will do the trick:
//Setup a sample array
int[] a = new int[2];
a[0] = 2;
a[1] = 4;
//Convert each item to a string, convert that to a string array, join the strings and turn into an int
int output = int.Parse(String.Join("", a.Select(s => s.ToString()).ToArray()));
This works for me:
int number = 12345;
string result1 = "";
string result2 = "";
string numberString = number.ToString();
for (int i = 0; i < numberString.Length; i++ )
{
if (numberString[i] % 2 == 0)
{
result1 = result1 + numberString[i];
}
else
{
result2 = result2 + numberString[i];
}
}
int evenNumbers = int.Parse(result1);
int oddNumbers = int.Parse(result2);
How can I build two INT varabile
when each one contains all of the
numbers together from the array?
I can't say for sure, but I think you're asking how to assemble a number given each of its digits in decreasing order of significance.
To 'append' a digit to a number, you can multiply the number by 10 and then add the digit to that. To create the 'assembled' number, you can perform this operation for each digit in the array,
int[] digits = ...
int num = digits.Aggregate(0, (numSoFar, digit) => 10 * numSoFar + digit);
As a loop, this would look like:
int num = 0;
foreach(int digit in digits)
{
num = 10 * num + digit;
}
Try this with LINQ,
int num = 92345;
string strNum = Convert.ToString(num);
var divisibleby2 = from c in strNum
where int.Parse(c.ToString()) % 2 == 0
select c.ToString();
var notDivisibleby2 = from c in strNum
where int.Parse(c.ToString()) % 2 != 0
select c.ToString();
int int_divisibleby2num = int.Parse(String.Join("", divisibleby2.ToArray()));
int int_Notdivisibleby2num = int.Parse(String.Join("", notDivisibleby2.ToArray()));
Every programmer should write wacky code at least once a day:
int checkCount = 12345, numEven, numOdd;
Boolean result;
result = int.TryParse(checkCount.ToString().Replace("0", "").Replace("2", "").Replace("4", "").Replace("6", "").Replace("8", ""), out numOdd);
result = int.TryParse(checkCount.ToString().Replace("1", "").Replace("3", "").Replace("5", "").Replace("7", "").Replace("9", ""), out numEven);
Another solution could be...
var num1 = 94321;
var oddFinal = 0;
var evenFinal = 0;
var odd = new List<int>();
var even = new List<int>();
while( num1>0 )
{
if( num1 % 2 == 0 )
odd.Add( num1 % 10 );
else
even.Add( num1 % 10 );
num1 = num1 / 10;
}
for (int i = 0; i < odd.Count; i++)
{
oddFinal += odd[i] * (int) Math.Pow(10,i);
}
for (int i = 0; i < even.Count; i++)
{
evenFinal += even[i] * (int) Math.Pow(10,i);
}

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