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.
Related
public static void Main()
{
EvenNumbers();
}
public static void EvenNumbers()
{
int written = int.Parse(Console.ReadLine());
for (int i = 0; i <= written; i++)
{
if (i % 2 == 1)
continue;
Console.WriteLine(i);
}
}
}
}
Yes I'm aware I've declared the code in a different method from the main method despite with a program this simple there being no need to its just for simple practice. I'm just wondering as you can see in the code it detects the input of the user and then from that input uses a for loop and counts up to it evenly. However, I want it to count up to it by odds if I put an odd number in. How could I do this?
Check for i % 2 != written % 2.
To print odd or even numbers, the line if (i % 2 == x) needs to have x=1 to print even numbers and x=0 to print odd numbers. If you take written % 2 you will get 0 if it is even and 1 if it is odd. Since you want to print even numbers if the input number is even and odd numbers if the input is odd, you store a number in the variable modNumber that you will then use in place of x in if (i % 2 == x). The line int modNumber = written % 2 == 1 ? 0 : 1 in English means "The int modNumber equals 0 if written % 2 == 1, otherwise it equals 1".
public static void EvenNumbers()
{
int written = int.Parse(Console.ReadLine());
int modNumber = written % 2 == 1 ? 0 : 1;
for (int i = 0; i <= written; i++)
{
if (i % 2 == modNumber)
continue;
Console.WriteLine(i);
}
}
You just need to count by twos. That will work for either even or odd numbers. For odd numbers, you need to start at 1, and for even numbers, you need to start at 0. You can easily figure out which you need by doing a single mod operation. x % 2 will be 1 for odd numbers, and zero for even numbers.
public static void Count()
{
int written = int.Parse(Console.ReadLine());
for (int i = written % 2; i <= written; i += 2)
{
Console.WriteLine(i);
}
}
I am trying to fasten my isPrime function but when I add a condition that if the number is divisible by 2 just return false instead of doing the whole process to find if the number is prime or not, but when I do this, it skips me a number for example the 6th prime is 13, without the condition if it's divisble by 2 I get 13, but when I add it I get 17.
static bool isPrime(long n)
{
bool prime = false;
int div = 0;
if (n % 2 == 0)
return false;
else
for (long i = 1; i < n + 1; i++)
{
if (n % i == 0)
div++;
if (div == 2)
prime = true;
else
prime = false;
}
return prime;
}
You need to check for the special case of 2 first, it's even but prime.
As an additional optimization, you can improve the bounds you're looping up to; there's no need to go as high as n + 1.
If you want to speed up the solution you can do something like that:
static bool isPrime(long n) {
// all integers less than 1 (1 is included) are not prime
if (n <= 1)
return false;
// Error in your code: 2 is prime, even if other even numbers aren't
if (n % 2 == 0)
return (n == 2);
// there's no need to loop up to n: sqrt(n) is quite enough
long max = (long) (Math.Sqrt(n) + 0.1);
// skip even numbers when looping: i +=2
for (long i = 3; i <= max; i += 2) {
// the early return the better
if (n % i == 0)
return false;
}
return true;
}
if (n % 2 == 0)
return (n == 2);
Modulus operation is slow in most architectures if you compare it to bit level checking. You can choose to only check the least significant bit of each number and get the answer if it's even or odd number.
Just do a AND operation with 1 and the value. The result tells you if it's even.
Example:
100101011101 (the value to check)
000000000001 (bitmask to AND with)
000000000001 (the result after AND, still 1 ---> odd number (true in boolean))
So:
if(!(value & 1))
{
//even
return false;
};
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'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;
}
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to check if a number is a power of 2
I want to determine if a number is in
1
2
4
8
16
32
64
128
256
512
1024
2048
4096
8192
16384
...
I tried this:
public static void Main(string[] args)
{
int result = 1;
for (int i = 0; i < 15; i++)
{
//Console.WriteLine(result);
Console.WriteLine(result % 2);
result *= 2;
}
}
As you can see it returns
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
...
How should I efficiently make the above print to be 0 for all of them including 1?
The following expression should be true if i is in your sequence.
(i & (i-1)) == 0)
http://rextester.com/JRH41036
How about something like this?
bool IsInBinarySequence( int number ){
var numbertocheck = 1;
do{
if( number == numbertocheck ) return true;
numbertocheck *= 2;
}while( numbertocheck <= number );
return false;
}
This has no specific limit on the number to check, but makes sure it stops checking if the number to check grows larger than the actual number we're trying to decide if is in the binary sequence.
Since the first time result is odd, you will get 1, since right after that you multiply it by 2, you will always get 0.
You need to print result if you want to get the list of powers of 2.
Console.WriteLine(result);
A primitive way to do that will be:
public static void Main(string[] args)
{
int result = 1;
int numToCheck = 141234;
boolean found = false;
for (int i = 0; i < 15; i++)
{
if (numToCheck == result) {
found = true;
break;
}
result *= 2;
}
if(found) Console.WriteLine("Awesome");
}
You can determine if a number is a power of 2 (including 2^0) by using the following method:
public bool IsPowerOfTwo(int x) {
return (x > 0) && ((x & (x - 1)) == 0)
}
Over here you can read why and how this works.
It's a bit of a hack, but this works ...
static void Main()
{
for (int i = 0; i < 40; i++)
{
var str = Convert.ToString(i, 2);
var bitCount = str.Count(c => c == '1');
Console.ForegroundColor = bitCount == 1 ? ConsoleColor.White : ConsoleColor.DarkGray;
Console.WriteLine(i + ": " + (bitCount == 1));
}
}
it seems you're actually asking if only one bit in the binary representation of the number is a 1
What you is not a test whether the number is in the sequence BUT it is a generator for such numbers... only the print part is containing some sort of a test...
Try this code for a test:
public static void Main(string[] args)
{
int result = 0;
int numToTest = 0;
if ( int.TryParse (args[0], out numToTest) )
{
result = ((from c in Convert.ToString (numToTest, 2) where c == '1' select c).Count() == 1 ) ? 1 : 0;
}
Console.WriteLine(result);
}
The above code takes a commandline argument and tests it for being in the binary sequence according to the criterion you posted... if so it prints 1, otherwise it prints 0.
Thats correct. 1 0 0 0 0 0 is the correct sequence.
Result is 1 in the first loop. 1 % 2 is 1.
Then result *= 2 gives result the value 2. In the next loop run 2 % 2 = 0. Then result *= 2 is 4. 4%2 is 0. 4 *= 2 is 8. 8 %2 is 0. Since result is always multiplied with 2 it keeps to be in the powers of 2 row and thus als MOD operations with 2 result to 0. So all is fine with that code.
your code will print only Binary sequences. as you are applying MOD 2 . so either you will get 0 or 1 . so it will be print in Binary Sequence.
Boolean result = false;
Int32 numberToTest = 64;
Int32 limit = 15;
for (int i = 0; i < limit && !result; i++)
{
if (Math.Pow(2, i).Equals(numberToTest))
{
result = true;
}
}
Console.WriteLine(String.Format("Number {0} {1} a power of 2.", numberToTest, result ? "is" : "is not"));