How to take the sum of only even and odd numbers? C# - c#

When the user enters numbers, say 3 and 7, the program adds all of the number in between and the numbers the user entered. Now I need to make it add only the even and odds in between the numbers. This is what I have so far:
static void Exercise1()
{
int min;
int max;
int sum = 0;
int odd = 0;
int even = 0;
Console.WriteLine("Enter minimum integer: ");
min = int.Parse(Console.ReadLine());
Console.WriteLine("Enter maximum integer: ");
max = int.Parse(Console.ReadLine());
//Sum of all
Console.Write("All: ");
for (int x = min; x <= max; x++)
{
Console.Write(min);
min++;
Console.Write(" + ");
sum += x;
}
Console.Write("= ");
Console.Write(sum + "\n");
//Odd Numbers
Console.Write("Odd: ");
for (int x = min; x <= max; x++)
{
if (min % 2 != 0)
{
Console.Write(min);
min++;
Console.Write(" + ");
odd += x;
}
}
Console.Write("= ");
Console.Write(odd + "\n");
//Even Numbers
Console.Write("Even: ");
for (int x = min; x <= max; x++)
{
if (min % 2 == 0)
{
Console.Write(min);
min++;
Console.Write(" + ");
even += x;
}
}
Console.Write("= ");
Console.Write(even + "\n");
}
I can find the sum of all the numbers but what I have tried here is the extent of my knowledge. I have hit a dead end.

You're doing min++ within the loops, which means min is not what it should be. It is sometimes a reasonable micro-optimisation to do ++min and not have an x at all, but only if you're never going to need that value again.
You could speed things up by skipping x += 2 in each loop once you've found the odd (or even, accordingly), but speed things even more so by having one loop:
int sum = 0;
int odd = 0;
int even = 0;
for (int x = min; x <= max; x++)
{
sum += x;
if (x % 2 == 0)
even += x;
else
odd += x;
}
However you can do much better with a bit of mathematical thinking on it.
∑[x, y] = (y - x + 1)(y + x)/2
E.g. from 5 to 9 is 5 + 6 + 7 + 8 + 9 = 35 and also is (9 - 5 + 1) * (5 + 9) / 2 = 35.
So to find the sum you don't need a loop, you need:
int sum = (max - min + 1) * (max + min) / 2;
This would make a big difference in speed if min was -1024 and max was 8980 because you can just do this calculation and get 39799890 rather than having to loop through 10005 different values.
Similarly if you find the min even number (minEven = min % 2 == 0 ? min : min + 1) and the max even number (maxEven = max % 2 == 0 ? max : max - 1) then you can find the sum of evens with:
int sumEven = ((maxEven - minEven) / 2 + 1) * (maxEven + minEven) / 2;
And indeed the exact same formula works for odd:
int sumOdd = ((maxOdd - minOdd) / 2 + 1) * (maxOdd + minOdd) / 2;
There, there's no need to do any looping at all, and your Θ(n) approach can be replaced with a Θ(1) approach.

The problem is that you are confusing the roles of x and min. min is entered by the user and serves as the starting point for your method; you shouldn't be changing it. However, you change min during each iteration of your for loops. So first of all, remove min++ from all three of your for loops.
x is a variable that changes as your find the sums. So instead of Writing the value of min to console (this value should be constant, you are really trying to find out what the value of x is... So, change your Console.Write(min) to Console.Write(x)
Also change your if-statement from
if (min % 2 != 0)
to
if (x % 2 != 0)
You can brush up on the for-loop (and other) control statements by reading this lesson or watching this video.

Here's a way worth looking at:
static void Exercise1()
{
Console.WriteLine("Enter minimum integer: ");
int min = int.Parse(Console.ReadLine());
Console.WriteLine("Enter maximum integer: ");
int max = int.Parse(Console.ReadLine());
IEnumerable<int> all = Enumerable.Range(min, max - min + 1);
IEnumerable<int> odds = all.Where(n => n % 2 == 1);
IEnumerable<int> evens = all.Where(n => n % 2 == 0);
Console.WriteLine(String.Format("All: {0} = {1}", String.Join(" + ", all), all.Sum()));
Console.WriteLine(String.Format("Odd: {0} = {1}", String.Join(" + ", odds), odds.Sum()));
Console.WriteLine(String.Format("Even: {0} = {1}", String.Join(" + ", evens), evens.Sum()));
}
That should give you something to thing about.

Related

Can you please help me with a clue on how can I find all possible combinations for a given set of number from 1 to N, using +- operators [duplicate]

This question already has answers here:
Linq query to get all numbers (positive and negative) up to N that sum up to number K
(5 answers)
Listing all permutations of a string/integer
(28 answers)
Closed 1 year ago.
Given input: N = 6, X = 3
The output should be:
1 + 2 + 3 - 4 - 5 + 6 = 3
1 + 2 - 3 + 4 + 5 - 6 = 3
1 - 2 - 3 - 4 + 5 + 6 = 3
So far I could manage this:
//returns a string of numbers from 1 to N
static string Numbers(int maxNumber) => maxNumber > 1 ? Numbers(maxNumber - One) + maxNumber :"1";
and a function that generates all possible combinations for +- but the problem is that I want to combine the +- resulted string with numbers from 1 to N:
static void Permute(char[] arry, int i, int n)
{
int j;
if (i == n)
Console.WriteLine(arry);
else
{
for (j = i; j <= n; j++)
{
Swap(ref arry[i], ref arry[j]);
Permute(arry, i + 1, n);
Swap(ref arry[i], ref arry[j]); //backtrack
}
}
}
static void Swap(ref char a, ref char b)
{
char tmp;
tmp = a;
a = b;
b = tmp;
}
This looks like a very different form of "permute". For N integers, you have D=N-1 decisions to make, each of which can be either a + or a -. Two options is: "binary", so, if this is me, I would compute (2^D)-1 (which gives us the upper bound), then do a for loop from zero to that number (inclusive), and do the math: each binary digit is a decision point, and we could say 0===- and 1===+; see what the result is: if it is the number you wanted: log it.
For N=6 we have D=5, and 32 attempts to do; 0 thru 31:
int N = 6, X = 3;
// how many decisions is that?
var decisions = N - 1;
// treat each -/+ as one of "decisions" binary digits
var binaryUpperLimit = (1 << decisions) - 1;
for (int i = 0; i <= binaryUpperLimit; i++)
{
// compute the sum
int sum = 1; // the 1 is a permenant fixture, it seems
// determine each decision using binary arithmetic
for (int place = 0; place < decisions; place++)
{
int digit = place + 2;
if ((i & (1 << place)) == 0)
{
sum -= digit;
}
else
{
sum += digit;
}
}
// is that what we wanted?
if (sum == X)
{
// we have a "hit"; repeat the above to output this
Console.Write("1");
for (int place = 0; place < decisions; place++)
{
if ((i & (1 << place)) == 0)
{
Console.Write(" - ");
}
else
{
Console.Write(" + ");
}
int digit = place + 2;
Console.Write(digit);
}
Console.Write(" = ");
Console.WriteLine(sum);
}
}
(if the initial 1 can be negative, you'll need to adjust to add an extra decision, start the sum at zero, and make digit be +1 instead of +2)

Why is my code not returning the sum using while loop?

I'm trying to find the sum from (1 to n) or given number.
using this code:
int n;
int counter = 0;
int sum = 0;
Console.Write("Please enter the sum limit number: ");
n = int.Parse(Console.ReadLine());
//around here is where code freezes and nothing else happens
while(counter <= n)
{
counter = +1;
sum = sum + counter;
}
Console.Write("The sum from 1 - " + n + " =" + sum);
I know I can use:
int n;
int counter = 0;
int sum = 0;
Console.Write("Please enter the sum limit number: ");
n = int.Parse(Console.ReadLine());
var sum = Enumerable.Range(1, n);
Console.Write("The sum from 1 - " + n + " =" + sum.Sum());
but my next challenge is to only add the numbers that are divisible by 3 or 5, so I'm planning on doing:
if (sum % 3 == 0 | sum % 5 == 0)
{
total = total + sum;
}
What is wrong with my method? Also, alternative ways to do this are more than appreciated!
To get out of while loop, condition needs to satisfy.First you need increment counter present in while loop.
To increment counter variable either you can try counter++/++counter i.e. post/pre increment operator or you can do counter += 1/ counter = counter + 1.
Something similar to
//around here is where code freezes and nothing else happens
while(counter <= n)
{
counter += 1; // not counter=+1;
sum = sum + counter;
}
Reference: Increment decrement in C#
if you want to increment the counter you should either use
counter = counter + 1;
or
counter++;
or
counter += 1;

Sum of numbers and cubing numbers in C#

Hey I am slightly new to C# it has been a week today. Ive managed to get this far but I cant seem to just out put the sum of the even numbers I've cubed i get the whole output and the last number is the total summed except i just want the last to show. Any help would be much appreciated and apologies for the horrendous code. Thanks
using System;
public class Test
{
public static void Main()
{
int j = 0; //Declaring + Assigning the interger j with 0
int Evennums = 0; // Declaring + Assigning the interger Evennums with 0
int Oddnums = 0; //Declaring + Assigning the interger Oddnums with 0
System.Console.WriteLine("Calculate the sum of all even numbers between 0 and the user’s number then cube it!"); //Telling console to write what is in ""
Console.WriteLine("Please enter a number");
uint i = uint.Parse(Console.ReadLine());
Console.WriteLine("You entered: " + i);
Console.WriteLine("Your number cubed: " + i*i*i);
if (i % 2 == 0)
while (j <= i * i * i)
{
if(j % 2 == 0)
{
Evennums += j; //or sum = sum + j;
Console.WriteLine("Even numbers summed together " + Evennums);
}
//increment j
j++;
}
else if(i%2 != 0)
//reset j to 0 like this: j=0;
j=0;
while (j<= i * i * i)
{
if (j%2 == 0)
{
Oddnums += j;
//Console.WriteLine(Oddnums);
}
//increment j
j++;
}
}
}
if you want to show the last sum, but not every summing process, change the location of print statement
if (i % 2 == 0)
{
while (j <= i * i * i)
{
if(j % 2 == 0)
{
Evennums += j; //or sum = sum + j;
}
//increment j
j++;
}
Console.WriteLine("Even numbers summed together " + Evennums);
}
same thing applies for the else if block.
You could try to achieve that you want like below, using LINQ:
// Calculate the cube of i.
int cube = i*i*i;
int sum = 0;
string message;
// Check if cube is even.
if(cube%2==0)
{
sum = Enumerable.Range(0,cube).Where(x => x%2==0).Sum();
message = "The sum of the even numbers in range [0,"+cube+"] is: ";
}
else // The cube is odd.
{
sum = Enumerable.Range(0,cube).Where(x => x%2==1).Sum();
message = "The sum of the odd numbers in range [0,"+cube+"] is: ";
}
// Print the sum.
Console.WriteLine(message+sum);

C# - What's wrong with my conversion from double to int?

I keep getting this error:
"Cannot implicitly convert type 'double' to 'int'. An explicit
conversion exists (are you missing a cast?)"
Code:
Console.WriteLine("ISBN-Prüfziffer berechnen");
Console.WriteLine("=========================");
Console.WriteLine();
Console.Write("ISBN-Nummer ohne Prüfziffer: ");
string ISBNstring = Console.ReadLine();
int ISBN = Convert.ToInt32(ISBNstring);
int PZ;
int i;
double x = Math.Pow(3, (i + 1) % 2);
int y = (int)x;
for (i = 1; i <= 12; i++)
{
PZ = ((10-(PZ + ISBN * x) % 10) % 10);
}
Console.WriteLine(PZ);
Console.ReadLine();
Here is the new code:
Console.WriteLine("ISBN-Prüfziffer berechnen");
Console.WriteLine("=========================");
Console.WriteLine();
Console.Write("ISBN-Nummer ohne Prüfziffer: ");
string ISBNstring = Console.ReadLine();
long ISBN = Convert.ToInt32(ISBNstring);
long ISBN1 = (Int64)ISBN;
int PZ = 0;
int i;
for (i = 1; i <= 12; i++)
{
double x = Math.Pow(3, (i + 1) % 2);
long y = (double)x;
PZ = ((10 - (PZ + ISBN * y) % 10) % 10);
}
Console.WriteLine(PZ);
Console.ReadLine();
But I'm still getting a conversion error for double to long and long to int...
I think you meant to use your y variable here instead of x :
PZ = ((10-(PZ + ISBN * y) % 10) % 10);
As a side note, you'll get compilation errors on both PZ and i, you need to initialize their values before using them, e.g. int PZ = 0; and int i = 0;
And please, use meaningful names; PZ, i, x and y don't mean anything to someone reading your code, or even to you in a few weeks.
Okay, I've modified it a little...
Console.WriteLine("ISBN-Prüfziffer berechnen");
Console.WriteLine("=========================");
Console.WriteLine();
Console.Write("ISBN-Nummer ohne Prüfziffer: ");
string ISBNstring = Console.ReadLine();
int sum = 0;
for (int i = 0; i < 12; i++)
{
int digit = ISBNstring[i] - '0';
if (i % 2 == 1)
{
digit *= 3;
}
sum += digit;
}
int result = 10 - (sum%10);
Console.WriteLine(result);
Console.ReadLine();
Here's the changes :
- You can declare i directly in your for loop, it'll save you a line.
- Instead of putting the ISBN into a long, keep in in a string. Just iterate over each character one by one.
- Each digit can be obtained by taking the ASCII value, and removing the value of 0.
- The % 2 == 1 thing is basically "If the number is at an odd position", where you can apply the *3. This replaces your Math.Pow that wasn't very clear.

C# return multiples of a number in a number and the remainder?

I want to find all multiples of 3 given a certain number, and also find the remainder.
So for example:
Given the number 10 : multiples of 3 = {3;6;9} + remainder = 1
Given the number 11 : multiples of 3 = {3;6;9} + remainder = 2
The algorithm I have so far (but not code) goes like this:
Check if X is a multiple of 3 - Yes - return multiples (no remainder);
No? is x-1 a multiple of 3 - Yes - return multiples (1 remainder);
No? is x-2 a multiple of 3 - Yes - return multples (2 remainder);
Is there a better way to do this, using less code?
Edit: 2 more things, I'm only looking for 3 - so this could be a const. Also any number smaller than 3: 2, 1 and 0 - I don't mind having additional logic for that.
IEnumerable<int> Foo(int n, int k)
{
int m = k;
while (m <= n)
{
yield return m;
m += k;
}
yield return m - n;
}
Integer division (/) and modulus (%) are your friends here:
var multiples = num / 3;
var remainder = num % 3;
x = given number
y = loop number
have y loop from 0 to x while increasing it by 3 every time.
if y > x then the remender is (x-(y-3))
You can use the divider / and the modulus %
http://msdn.microsoft.com/en-us/library/3b1ff23f.aspx
10 / 3 = 3
http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx
10 % 3 = 1
int number = 10;
int divisor = 3;
List<int> numbers;
// Find all the numbers by incrementing i by the divisor.
for(int i = 0; i < number; i += divisor)
{
numbers.Add(i);
}
// Find the remainder using modulus operator.
int remainder = number % divisor;
You can simply enumerate the output values
public static IEnumerable<int> GetMultiples(int value, int divisor) {
// Be care of negative and zero values...
if ((value <= 0) || (divisor <= 0))
yield break;
// Multiplications
for (int i = 1; i <= value / divisor; ++i)
yield return i * divisor;
// Finally, let's return remainder if it's non-zero
if ((value % divisor) != 0)
yield return value % divisor;
}
...
foreach(int item in GetMultiples(10, 3)) { // item will be 3, 6, 9, 1
...
}
Here's your exact output
private static void Main(string[] args)
{
int num = 10;
int divisor = 3;
if(num<divisor)
Console.Write(num + " is less than " + divisor);
Console.Write("Given the number " + num + " : multiples of " + divisor + " = {");
for (int i = divisor; i < num; i+=divisor)
Console.Write((i!=3) ? ";"+i : i.ToString());
Console.Write("} + remainder = " + num%divisor);
}
Output
Given the number 10 : multiples of 3 = {3;6;9} + remainder = 1
and checks if input is less than divisor
You can use operator modulo
%
But is very slowly if you use a lot...
This will give you the output you want:
int num;
Console.WriteLine("give me a number equal or above 3!");
int.TryParse(Console.ReadLine(),out num);
int i = 0;
List<int> nums = new List<int>();
i += 3;
while (i <= num)
{
nums.Add(i);
i += 3;
}
Console.Write("Numbers are: ");
foreach (int y in nums)
{
Console.Write(y + " , ");
}
Console.WriteLine("The remainder is " + (num - nums[nums.Count - 1]));
Wasn't LINQ built for EXACTLY for this?
IEnumerable<int> GetMultiples(int max)
{
return Enumerable.Range(1, max / 3)
.Select(p => p * 3)
.Concat((max %= 3) == 0 ? new int[0] : new int[] { max });
}

Categories