I need help with a simple C# program. Simpley yet I don't know the solution. The problem is here: I need to loop (or print on the screen) all numbers in this order: 2, -3, 4, -5, 6, -7, etc. until they reach 100.
Do you have any ideas how to do that? For now I've done something like that:
for (int i = -2; i <= 100; i += 1)
{
Console.WriteLine(i);
}
But I can't get it to work like the order I want, I know I'm doing something wrong in the i += 1 section but I can't figure out how to do that! Thank you for your support.
You can multiple with -1 on odd numbers, therefore use the % operator:
for (int i = 2; i <= 100; i++)
{
int val = i % 2 == 1 ? i * -1 : i;
Console.WriteLine(val);
}
Demo
for(int i=2;i<=100;++i){
Console.WriteLine(i % 2 == 1 ? -i : i);
}
Pretty simple if we use modulo
The steps are faily straight forward. If we will notice the it's the same solution as printing 2-100 but with 1 little twist, for the odd places the number i should be at his negative sign. So the solution will be the same.
Steps:
Loop i to 100
For every iteration we will decide if it's odd or even.
If i is even will multiply it by 1 that will result with i of course. else, that means it's odd and thus, resulting in
multiplying with -1, resulting with minus i.
Code
for (int i = 2; i <= 100; i++)
{
Console.WriteLine(i * (i%2 == 0 ? 1 : -1));
}
You should iterate from 2 to 100 one by one (yes, all are positive values)
Then in loop body you should invert sign on each iteration (by multiplying on "-1") and print the result on screen.
Using bitwise and to spot the odd numbers:
for (int i = 2; i <= 100; i += 1)
{
int toPrint = i
if((i & 1)==1)
{
// It's odd
toPrint = -toPrint;
}
Console.WriteLine(toPrint);
}
static void Main(string[] args)
{
for (int i = 2; i <= 100; i++)
{
if (i % 2 == 1)
{
int j = -i;
Console.WriteLine(j);
}
else
Console.WriteLine(i);
}
Console.ReadLine();
}
As we all did this task in school:
Enumerable.Range(2, Int32.MaxValue - 1)
.TakeWhile(i => i <= 100)
.Select(i => i % 2 == 0 ? i : -i)
.ToList()
.ForEach(Console.WriteLine);
Related
I'm trying to learn C# by solving mathematical problems. For example, I'm working on finding the sum of factors of 3 or 5 in the first 1000 positive numbers. I have the basic shell of the code laid out, but it isn't behaving how I'm expecting it to.
Right now, instead of getting a single output of 23, I am instead getting 1,1,3,3,5,5,7,7,9,9. I imagine I messed up the truncate function somehow. Its a bloody mess, but its the only way I can think of checking for factors. Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
using System;
namespace Problem1
{
class Problem1
{
public static void Main()
{
//create a 1000 number array
int[] numberPool = new int[10];
//use for loop to assign the first 1000 positive numbers to the array
for (int i = 0; i < numberPool.Length; i++)
{
numberPool[i] = i + 1;
}
//check for factors of 3 or 5 using if/then statment
foreach (int i in numberPool)
if ((i / 3) == Math.Truncate((((decimal)(i / 3)))) || ((i / 5) == Math.Truncate(((decimal)(i / 5)))))
{
numberPool[i] = i;
}
else
{
numberPool[i] = 0;
}
//throw the 0s and factors together and get the sum!
int sum = 0;
for (int x = 0;x < numberPool.Length;x++)
{
sum = sum + numberPool[x];
}
Console.WriteLine(sum);
Console.ReadLine();
//uncomment above if running in vbs
}
}
}
The foreach loop has a few errors.
If you want to modify the array you are looping through use a for loop. Also, use modulus when checking remainders.
for (int i = 0; i < numberPool.Length; i++)
{
if (numberPool[i] % 3 == 0 || numberPool[i] % 5 == 0)
{
// Do nothing
}
else
{
numberPool[i] = 0;
}
}
Modulus (%) will give the remainder when dividing two integers.
Another useful shortcut, variable = variable + x can be replaced with variable += x
Please note that there are more concise ways of doing this but since you are learning the language I will leave that for you to find.
#kailanjian gave some great advice for you but here is another way your initial logic can be simplified for understanding:
//the sum of factors
int sum = 0;
//the maximum number we will test for
int maxNum = 1000;
//iterate from 1 to our max number
for (int i = 1; i <= maxNum; i++)
{
//the number is a factor of 3 or 5
if (i % 3 == 0 || i % 5 == 0)
{
sum += i;
}
}
//output our sum
Console.WriteLine(sum);
You also stated:
Second, I think that the output is writing during the loop, instead of patiently waiting for the for() loop to finish.
Your program logic will execute in the order that you list it and won't move on to the next given command until it is complete with the last. So your sum output will only be printed once it has completed our for loop iteration.
TLDR: Codility "Challenge" - my results: Where is the error?
Short Description (Full Description): Given an Array, split the array into two (Upper and lower parts) and give the minimum difference between two possible parts in absolute value.
My thought process is:
create an "Upper" and "Lower" bucket for sums.
In one pass of the array, we get a sum for the "Upper" bucket.
Then, one array value at a time, move the numbers into lower (Upper-n, Lower+n).
At each step, get the difference (Abs(Upper-lower))
Monitor lowest "Minimum"
Submitted Code:
public int solution(int[] A)
{
// Quick results:
if (A == null) return -1;
if (A.Length == 0) return -1; // Can't split
if (A.Length == 1) return -1; // Can't split
if (A.Length == 2) return Math.Abs(A[0] - A[1]); // Only one way to split
// Hold above/below/result...
long lower = 0;
long upper = 0;
var min = long.MaxValue;
// Pass#1: Sum All to get "Upper"
for (long i = 0; i < A.Length; i++) upper += A[i];
// Pass#2:
// foreach in array
// ... Shift number from upper to lower
// ... Calculate new difference/minimum
for (var i = 0; i < A.Length; i++)
{
lower += A[i];
upper -= A[i];
var diff = Math.Abs(upper - lower);
min = Math.Min(min, diff);
if (diff == 0) return 0;
}
return (int) min;
}
Out of 13 test cases, the only one that Codility fails me on is: "Small Numbers". it says "Wrong answer, expected 20 got 0". It doesn't show the test data it uses, so I'm left guessing as to "Why".
Where is my error? I think I've stared at it too much, but I can't seem to figure out what case would "break" my function.
Edit: Fixed translation. Submitted code to Codility uses a Foreach, and the code I have here is a For. Corrected the variables in the loop.
The problem is that you didn't take into account one of the rules: 0 < P < N.
Your second loop is assuming 0 < P <= N.
Assume this input:
10, 10, -20
Your code would return 0 but 40 would be correct.
Fix:
Change your second loop header to
for (var i = 0; i < A.Length - 1; i++)
Proof
I am trying to improve a list collection that i have to replace values that are divisible by two and 10 and replace everything that is divisible by two with dTwo and ten with dTen?
My code works with one divisible statment but not two.
var num = new List<string>();
for (int n = 0; n < 101; n++)
{
num.Add(n % 2 == 0 ? "dTwo" : n.ToString());
num.Add(n % 10 == 0 ? "dTen" : n.ToString());
}
Since any number that is divisible by 10 is also divisible by 2 you have to switch your addition statements, and continue with the next number if you have a number divisible by 10:
var num = new List<string>();
for (int n = 0; n < 101; n++)
{
if( n % 10 == 0)
{
num.Add("dTen");
}
else num.Add(n % 2 == 0 ? "dTwo" : n.ToString());
}
If I can I try avoid using loop controls out side of the defined construct of the actual loop, ie. I prefer to avoid using continue if I can, it sort of feels like using goto statements. For this case, I would go for the plain and simple approach which I believe is readable, maintainable and simple albeit a little more verbose.
You can switch the order of the if/else if statements to change the priority if required, in this case the n % 10 has priority
var num = new List<string>();
for (int n = 0; n < 101; ++n)
{
if (n % 10 == 0)
{
num.Add("dTen");
}
else if (n % 2 == 0)
{
num.Add("dTwo");
}
else
{
num.Add(n.ToString());
}
}
There are two approaches I would take here, the first is verbose, but conveys what you're trying to do in a very readable manner:
var num = new List<string>(101);
for (int i = 0; i < 101 ; i++)
{
if (i == 0)
{
num.Add(i.ToString());
}
else if (i % 10 == 0)
{
num.Add("dTen");
}
else if (i % 2 == 0)
{
num.Add("dTwo");
}
else
{
num.Add(i.ToString());
}
}
The second uses a more concise LINQ-y type approach, like this.
var num = Enumerable.Range(0, 101)
.Select(
n => n == 0 ? n.ToString() :
n % 10 == 0 ? "dTen" :
n % 2 == 0 ? "dTwo" :
n.ToString())
.ToList();
Note that I've also taken into account the 0 edge case, where 0 would otherwise get reported as being divisible by 10.
Which one you go for is largely up to your taste. Personally I'd go for the latter implementation, as it's concise but still conveys the intent of the code. Some very rudimentary tests I've just done shows that it'll execute faster as well.
I need to determine if all the digits of the sum of n numbers and swapped n are odd.
For example:
36 + 63 = 99 (9 and 9 are both odd)
409 + 904 = 1313 (1 and 3 are both odd)
Visual Studio builds my code and it runs, but it doesn't return an answer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
long num = Convert.ToInt64(Console.Read());
long vol = voltea(num);
long sum = num + vol;
bool simp = simpares(sum);
if (simp == true)
Console.Write("Si");
else
Console.Write("No");
}
static private bool simpares(long x)
{
bool s = false;
long [] arreglo = new long [1000];
while ( x > 0)
{
arreglo [x % 10] ++;
x /=10;
}
for (long i=0 ; i <= arreglo.Length ; i++)
{
if (arreglo [i]%2 != 0)
s = true;
}
return s;
}
static private long voltea(long x)
{
long v = 0;
while (v > 0)
{
v = 10 * v + x % 10;
x /= 10;
}
return v;
}
}
}
I'm not sure what's wrong with your code, but I was thinking an easier way to accomplish this would be to use strings, rather than doing all the divisions and mods by 10.
Convert original number to string, reverse the string, then convert that back to a long
Add the original and reversed numbers
Convert the sum to a string
Loop over the result string and check to see if each digit is odd
It's not too clear what you mean by "Doesn't return an answer".
Add:
Console.ReadKey();
Console.ReadLine();
At the end of your Main function. I'd hazard a guess that you're not seeing an answer because the console is closing on you.
EDIT:
Found it:
for (long i=0 ; i <= arreglo.Length ; i++)
Index out of bounds. That should be:
for (long i=0 ; i < arreglo.Length ; i++)
i should be "Less than" arreglo, not "Less than or equal to"
EDIT2:
This is why your current code is broken. I'd highly recommend also looking at alternative methods of solving the problem. See Andy White's Answer.
It looks to me like you might have an infinite loop and a loop that never enters.
// because v = 0, the while will never execute
long v = 0;
while (v > 0)
{
v = 10 * v + x % 10;
x /= 10;
}
So after pulling my hair out for 30 minutes, I have decided to come to SO for some help on this problem:
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Now, I don't want to know how to do the problem - that's easy - and especially not the answer. I would like to know why my code isn't giving me the correct answer when I run it (C#):
using System;
using System.Collections.Generic;
public class Euler010 {
public static bool isPrime(Int64 n) {
if (n <= 1)
return false;
if (n < 4)
return true;
if (n % 2 == 0)
return false;
if (n < 9)
return true;
if (n % 3 == 0)
return false;
Int64 r = (Int64)Math.Floor(Math.Sqrt((double)n));
Int64 f = 5;
while (f <= 4) {
if (n % f == 0)
return false;
if (n % (f + 2) == 0)
return false;
f += 6;
}
return true;
}
public static void Main() {
Int64 sum = 2;
for (Int64 n = 3; n <= 2000000; n+=2) {
if (isPrime(n)) {
sum += n;
}
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
When run to n <= 10, it outputs 17, like it should. When run to anything that's easy to compute by hand, it outputs the correct answer (like n <= 20 -> 77).
However, when I run this, it outputs 666667333337 which is wrong.
Any ideas?
Int64 f = 5;
while (f <= 4) {
Maybe I'm missing something here but these two lines don't seem to make sense. I'm fairly certain that the code posted above will never execute the body of the while loop.
Perhaps you meant to check if f is less than the square root of r?
You're not using the variable r in your loop, I assume you probably want to loop while f<=r?
Not what you are looking for, but you should probably use something like Sieve of Eratosthenes to generate your primes.
Plus the existing tests catch all non-primes below 20 (divisible by 2, 3, etc).