I'm kinda new at c# programming so take it easy on me.
I couldn't find the answer to my (most likely) simple an stupid question (there's no stupid questions!!) so I post here.
I need to write a program which shows numbers from 1 to 10 that aren't divisble by 2, 3 and 8 using "continue" instruction.
My code:
static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0 && i % 3 == 0 && i % 8 == 0) continue;
Console.Write("{0} ", i);
}
Console.ReadKey();
}
It doesn't work, tho. The main issue is using &/&& operator. It should return both true and true. Help :(
I need to write a program which shows numbers from 1 to 10 that aren't divisble by 2, 3 and 8 using "continue" instruction.
The minimum number that can be divided by 8 with no remainder is 8. So the only numbers that could qualify are 8, 9 or 10.
if (8 % 2 == 0 && 8 % 3 == 0 && 8 % 8 == 0) // false
if (9 % 2 == 0 && 9 % 3 == 0 && 9 % 8 == 0) // false
if (10 % 2 == 0 && 10 % 3 == 0 && 10 % 8 == 0) // false
None of the numbers 8, 9, 10 can be divided by 2, 3, and 8 with a remainder of 0, so of course all numbers would be printed out, as continue would never be triggered. Are you sure it's "2, 3, AND 8" and not "2, 3, OR 8"?
if ((i % 2 == 0 && i % 3 == 0) || (i % 8 == 0)) continue;
Related
I'm new at C# and trying to solve:
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
This is what I wrote
int i = 1;
while (i % 2 != 0 || i % 3 != 0 || i % 4 != 0 || i % 5 != 0 || i % 6 != 0 || i % 7 != 0 || i % 8 != 0
|| i % 9 != 0 || i % 10 != 0 || i % 11 != 0 || i % 12 != 0 || i % 13 != 0 || i % 14 != 0
|| i % 15 != 0 || i % 16 != 0 || i % 17 != 0 || i % 18 != 0 || i % 19 != 0 || i % 20 != 0)
{
i++;
}
It works the answer is right, but can I optimize it
Thank you!
approach with Linq
while (Enumerable.Range(2,19).Any(x => i % x != 0))
{
i++;
}
The simplest next step is to take your long list of i % x != 0 tests and turn it into a loop:
bool IsEvenlyDivisible(int value, int range)
{
for (int i = 2; i <= range; i++)
{
if (value % i != 0)
{
return false;
}
}
return true;
}
int i = 1;
while (!IsEvenlyDivisible(i, 20))
{
i++;
}
You can even turn this while loop into a for loop:
for (int i = 1; IsEvenlyDivisible(i, 20); i++)
{
}
You can then make the IsEvenlyDivisible method simpler using linq, see fubo's answer.
I am learning how to use untiy in my spare time by reading a beginners book and looking up stuff online in the book there is a exercise that asks me
to create a script that outputs the numbers from 1 to 10 in to the console but dose not output any multiple of 3 and 5 instead outputting the phrase "programming is awesome "
while i have achieved this task by using this code
using UnityEngine;
using System.Collections;
public class Loops : MonoBehaviour {
// Use this for initialization
void Start () {
for(int i = 1; i <= 10; i++)
{
if(i == 3 )
print ("Programming is Awesome!");
else if (i == 5)
print ("Programming is Awesome!");
else if (i == 6)
print ("Programming is Awesome!");
else if (i == 9)
print ("Programming is Awesome!");
else if (i == 10)
print ("Programming is Awesome!");
else
print (i);
}
}
}
i was wondering if there was any way to achieve the same result only by using less lines of code
You want to use the modulus (aka modulo) operator (%) for this task. It returns the remainder of a division, so when the result of a modulus operation is 0 you know you have a multiple of the divisor.
for (int i = 1; i <= 10; i++)
{
if(i % 3 == 0 || i % 5 == 0)
print("programming is awesome");
else
print(i);
}
for (int i = 1; i <= 10; i++)
{
print((i % 3 == 0 || i % 5 == 0)? "programming is awesome" : i));
}
check out also using ternary operator.
The point of this exercise is that you should calculate the multiples, not just make one condition for every value that you know is a multiple.
Use the modulo operator to check it a number is an even multiple of another. This shows what the modulo operator returns for some values:
i i % 3
------------
1 1
2 2
3 0
4 1
5 2
6 0
7 1
As you see, i % 3 evaluates to 0 when i is a multiple of three. You can use that to check if the number is a multiple of three:
if (i % 3 == 0) {
print ("Programming is Awesome!");
}
Now you should be able to do the same for five also, and incorporate it in your code.
Ways of doing this
if(i == 3 || i == 5 || i == 6 || i == 9 || i == 10){
print ("Programming is Awesome!");
}
else {
print (i);
}
Better way By Using the modulo operator
if( i % 3 == 0 || i % 5 == 0){
print ("Programming is Awesome!");
}
else {
print (i);
}
Use can also try
print((i % 3 == 0 || i % 5 == 0)? "Programming is Awesome!" : i));
I was trying a simple exercise that shows on the screen all of the numbers that are multiples of 3 or 5 between 1-1000. As everyone knows the way to find this is using the modulus operator(%) and, if the modulus division returns 0 the number is multiple of 3 or 5, whatever you're comparing, very simple.
The point is that for some reason when I compare the expression if (i % 3 == 0 || i % 5 == 0) the first number that matches is 363.
When I compare only with 3 if (i % 3 == 0) the first number that matches is 105, and finally when I compare with only 5 if (i % 5 == 0) the result is as expected, starting from 5.
I would like to know what's going on here, or is just something so simple that I can't see at this time of the night due to I'm falling asleep.
static void Main(string[] args)
{
long total = 0;
for (int i = 3; i <= 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
total += i;
Console.WriteLine(i.ToString());
}
}
Console.Read();
}
Actually, it always displaying the correct result but you can't see them because of your Console size.
Try:
for (int i = 3; i <= 1000; i++)
{
if (i % 3 == 0 || i % 5 == 0)
{
Console.WriteLine(i);
}
if (i % 100 == 0) Console.Read();
}
Press enter to see next 100 numbers.
Try redirecting your output to a file and looking at it. Use Program.exe > Output.txt to redirect and then open it in Notepad.
I'm a 17 year old student currently in software engineering and web development and im having trouble right now with some of my coding. I need to make a project that will alow the user to input a number anywherefrom 0 to 999 and tell whether it is a prime number or not. The code i have so far is....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void primeNumber()
{
int primeNumber1 = int.Parse(Request.Form["Text4"]);
if (primeNumber1 % 1 == 0 & ! (primeNumber1 % 2 == 0 &
primeNumber1 % 3 == 0 &
primeNumber1 % 4 == 0 &
primeNumber1 % 5 == 0 &
primeNumber1 % 6 == 0 &
primeNumber1 % 7 == 0 &
primeNumber1 % 8 == 0 &
primeNumber1 % 9 == 0))
{
Response.Write(" This is a prime number! ");
}
else
{
Response.Write(" This is not a prime Number! ");
}
}
}
... but i cannot get this program to display the correct answer. Any help would be greatly appreciated. Thanks!
You have got the concept of prime numbers wrong. Your code would for example report that 3 is not a prime number, because you check if the number divides evenly in three even if the number entered is three.
The simplest solution would be to loop from 2 and up to primeNumber1 - 1 and check if any of those divides evenly with the number. As you are using a loop, you also need a variable to hold what the result was, as you don't have a single expression that returns the result.
Something like:
bool prime = true;
for (int i = 2; i <= primeNumber1 - 1; i++) {
if (primeNumber1 % i == 0) {
prime = false;
}
}
This is of course the simplest possible solution that solves the problem, for reasonably small numbers. You can for example improve on the solution by exiting out of the loop as soon as you know that it's not a prime number.
You also don't need to loop all the way to primeNumber1 - 1, but only as high as the square root of the number, but you can find out about that if you read up on methods for checking prime numbers.
You need to handle the special cases of 1 and 2 also. By definition 1 is not a prime number, but 2 is.
http://en.wikipedia.org/wiki/Prime_number
bool IsPrime(int number) {
if (number == 1) return false;
if (number == 2) return true;
for (int i = 2; i < number; ++i) {
if (number % i == 0) return false;
}
return true;
}
A little google-fu or a little navel-gazing about prime numbers in general, will lead you to the naive algorithm:
For all n such that 0 < n:
There are two "special case" prime numbers, 1 and 2.
All even numbers > 2 are non-prime, by definition
If you think about the nature of factoring, the largest possible factor you have to consider is the square root of n, since above that point, the factors are reflexive (i.e., the possible factorizations of 100 are 1*100 , 2*50 , 4*25 , 5*20 , 10*10 , 20*5 , 25*4, 50*2 and 100*1 — and the square root of 100 is...10).
That should lead you to an implementation that looks something like this:
static bool IsPrime( int n )
{
if ( n < 1 ) throw new ArgumentOutOfRangeException("n") ;
bool isPrime = true ;
if ( n > 2 )
{
isPrime = ( 0 != n & 0x00000001 ) ; // eliminate all even numbers
if ( isPrime )
{
int limit = (int) Math.Sqrt(n) ;
for ( int i = 3 ; i <= limit && isPrime ; i += 2 )
{
isPrime = ( 0 != n % i ) ;
}
}
}
return isPrime ;
}
Anytime you find yourself in programming repeating a test on a sequential range of numbers you're doing the wrong thing. A better construct for this is a loop. This will give you the range of numbers in an identifier which can then be used to write the repetive code one time. For example I could rewrite this code
primeNumber1 % 2 == 0 &
primeNumber1 % 3 == 0 &
primeNumber1 % 4 == 0 &
primeNumber1 % 5 == 0 &
primeNumber1 % 6 == 0 &
primeNumber1 % 7 == 0 &
primeNumber1 % 8 == 0 &
primeNumber1 % 9 == 0))
As follows
bool anyFactors = false;
for (int i = 2; i <= 9; i++) {
if (primeNumber1 % i != 0) {
anyFactors = true;
break;
}
}
At this point I can now substitute the value allTrue for the original condition you wrote.
if (primeNumber1 % 1 == 0 && !anyFactors)
I can also expand the number of values tested here by substiting a different number for the conditional check of the loop. If I wanted to check 999 values I would instead write
for (int i = 2; i <= 999; i++) {
...
}
Additionally you don't want to use & in this scenario. That is for bit level and operations. You are looking for the logical and operator &&
Try the code below:
bool isPrimeNubmer(int n)
{
if (n >=0 && n < 4) //1, 2, 3 are prime numbers
return true;
else if (n % 2 == 0) //even numbers are not prime numbers
return false;
else
{
int j = 3;
int k = (n + 1) / 2 ;
while (j <= k)
{
if (n % j == 0)
return false;
j = j + 2;
}
return true;
}
}
Today I was writing a program in C#, and I used % to calculate some index... My program didn't work, so I debugged it and I realized that "%" is not working like in other program languages that I know.
For example:
In Python % returns values like this:
for x in xrange (-5, 6):
print x, "% 5 =", x % 5
-5 % 5 = 0
-4 % 5 = 1
-3 % 5 = 2
-2 % 5 = 3
-1 % 5 = 4
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
In C#:
for (int i = -5; i < 6; i++)
{
Console.WriteLine(i + " % 5 = " + i % 5);
}
-5 % 5 = 0
-4 % 5 = -4
-3 % 5 = -3
-2 % 5 = -2
-1 % 5 = -1
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
Did I do something wrong or is % not working like it should?
As explained in the comments, the different behaviour is by design. The different languages just ascribe different meanings to the % operator.
You ask:
How can I use modulus operator in C#?
You can define a modulus operator yourself that behaves the same way as the Python % operator:
int mod(int a, int n)
{
int result = a % n;
if ((result<0 && n>0) || (result>0 && n<0)) {
result += n;
}
return result;
}
Both answers are correct. Although personally I think the "always positive" one makes more sense.
You can define your own modulus function that only gives positive answers like this:
int mod(int a, int n) {
return ((a%n)+n) % n;
}
In modular arithmetic, one defines classes of numbers based on the modulo. In other words, in modulo m arithmetic, a number n is equivalent (read: the same) to n + m, n - m, n + 2m, n - 2m, etc.
One defines m "baskets" and every number falls in one (and only one) of them.
Example: one can say "It's 4:30 pm" or one can say "It's 16:30". Both forms mean exactly the same time, but are different representations of it.
Thus both, the Python and C# results are correct! The numbers are the same in the modulo 5 arithmetic you chose. It would also have been mathematically correct to return (5, 6, 7, 8, 9) for example. Just a bit odd.
As for the choice of representation (in other words, the choice on how to represent negative numbers), that is just a case of different design choices between the two languages.
However, that is not at all what the % operator actually does in C#. The % operator is not the canonical modulus operator; it is the remainder operator. The A % B operator actually answer the question "If I divided A by B using integer arithmetic, what would the remainder be?"
— What's the difference? Remainder vs Modulus by Eric Lippert
Quick snippet to get the canonical modulus:
return ((n % m) + m) % m;
Test implementation:
Mono/C#:
machine:~ user$ cat mod.cs
using System;
public class Program
{
public static void Main (string[] args)
{
Console.WriteLine(Mod(-2, 5));
Console.WriteLine(Mod(-5, 5));
Console.WriteLine(Mod(-2, -5));
}
public static int Mod (int n, int m)
{
return ((n % m) + m) % m;
}
}
machine:~ user$ mono mod.exe
3
0
-2
Python:
machine:~ user$ cat mod.py
print -2%5;
print -5%5;
print -2%-5;
machine:~ user$ python mod.py
3
0
-2