As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
When solving "fizz-buzz" in C# using a "while" loop, I found out that first I should find the multiples of both 3 and 5 (multiples of 15) and then go to the multiples of 3 and 5 like below.
int myval = 0;
while (myval < 100)
{
myval = myval + 1;
if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz");
}
else if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else
{
listBox1.Items.Add(myval);
}
}
But if I write the code to filter multiples of 3 and 5 first and then go to the multiples of both 3 and 5 (multiples of 15) like below the end result only shows the fizz (multiples of 3) and buzz (multiples of 5) without fizz-buzz (multiples of both 3 and 5). Does anyone know what's the reason for this even IDE doesn't show me any errors.
myval = 0;
while (myval < 100)
{
myval = myval + 1;
if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz"); // for multiples of both 3 and 5
}
else
{
listBox1.Items.Add(myval);
}
}
Because it satisfies the first two conditions. So it will never hit your third else statement.
This boils down to the fact that if-else statements are processed sequentially. As soon as a condition that evaluates to true is encountered, the other else if clauses are skipped.
Suppose that a and b are both true. When you write
if (a) {
Foo1();
}
else if (b) {
Foo2();
}
you do not execute both Foo1 and Foo2. Since a is true, Foo1 executes and b is not even evaluated.
Now consider your problem. Consider the number 15. All three candidate divisors, 3, 5 and 15, divide into that number.
if (myval % 3 == 0)
{
listBox1.Items.Add("fizz");
}
else if (myval % 5 == 0)
{
listBox1.Items.Add("buzz");
}
else if (myval % 15 == 0)
{
listBox1.Items.Add("fizzbuzz"); // for multiples of both 3 and 5
}
else
{
listBox1.Items.Add(myval);
}
Since the multiples of 15 are also multiples of 3 (and 5), you will never even reach the myval % 15 == 0 test for multiples of 15.
It's because something divisible by 3 and 5 is also divisible by 3 and by 5. If you catch either of those conditions first, the later condition is never checked.
You could also write it like so:
var resultString = "";
if(myval % 3 == 0) resultString += "fizz";
if(myval % 5 == 0) resultString += "buzz";
if(myval % 5 != 0 && myval % 3 != 0) resultString += myval;
listBox1.Items.Add(resultString);
This will print all conditions without needing a separate check for % 15.
Also, I know this wasn't the original question, but typically someone wouldn't use a while loop to cycle through a range of numbers. Use a for loop for that:
for( int myval = 0; myval <= 100; myval++)
{
// code goes here
}
I always solved this a slightly different way: by constructing the string to add.
for (int myVal = 0; myVal < 100; myVal++)
{
string fb = "";
if ((myVal % 3) == 0) { fb = "fizz"; }
if ((myVal % 5) == 0) { fb += "buzz"; }
// Handle the case where it isn't divisible by 3 or 5:
if (fb == "") { fb = myVal.ToString(); }
// "output" the string.
listBox1.Items.Add(fb);
}
You can use this method to fill your Listbox:
foreach (int i in Enumerable.Range(1,100)){
string str = null;
listBox1.Items.Add((str = (i % 3 == 0 ? "fizz" : "")
+ (i % 5 == 0 ? "buzz" : "")) == ""
? i.ToString() : str );
}
Related
Here is my code, for my if statements I want to have it between two values for example:
if(rating < 5 > 2);
So I'm saying i want it to only print the command if that value is below 5 but higher than 2.
Is there a way to do this? Thank you for your time.
Here is my code.
public static void Main(string[] args)
{
Console.WriteLine("What would you rate starcraft out of 10?");
int rating = Console.Read();
if (rating < 5) ;
{
Console.WriteLine("Not good enough!");
Console.ReadLine();
}
if (rating > 5) ;
{
Console.WriteLine("OOOOOOOOO yeeeeeeee");
Console.ReadLine();
}
if (rating > 8) ;
{
Console.WriteLine("We are bestfriends now ;)");
Console.ReadLine();
Use conditional logical AND operator &&:
if (rating < 5 && rating > 2)
{
}
Or pattern matching (read more #1, read more #2):
if (rating is < 5 and > 2)
{
}
P.S.
You can refactor a bit with switch expression and ordering the checks to remove some code repetition and improve readability (note that original code does not cover rating == 5 case compared to the following):
var rating = ...;
var message = rating switch
{
< 2 => "Terrible",
< 5 => "Not good enough!",
< 8 => "OOOOOOOOO yeeeeeeee",
_ => "We are bestfriends now ;)"
};
Console.WriteLine(message);
Console.ReadLine();
To avoid complications, you can sort ratings' thresholds and then check them in order with a help of if ... else if pattern, e.g. having
2 - Nightmare
5 - Not good enough!
8 - OOOOOOOOO yeeeeeeee
more - We are bestfriends now
We can put it as
if (rating <= 2) // 2 or less
Console.WriteLine("Nightmare");
else if (rating <= 5) // (2..5]
Console.WriteLine("Not good enough!");
else if (rating <= 8) // (5..8]
Console.WriteLine("OOOOOOOOO yeeeeeeee");
else // more than 8
Console.WriteLine("We are bestfriends now");
Console.ReadLine();
Note: This is my first time using "Stack Overflow" and I am relatively new to C#
(please excuse my poor programming skills at the moment)
My Code:
static void Main(string[] args)
{
Challenge(5, 12);
}
static void Challenge(int num1, int num2)
{
//finds the sum of the two variables
int sum = num1 + num2;
Console.WriteLine("The sum of {0} and {1} is...\n{2}", num1, num2, sum);
bool isDivisible = true;
//checks if divisible by 5 and sets a value for 'isDivisible'
if ((sum % 10 == 5) || (sum % 10 == 0))
{
Console.WriteLine("\nThe sum is divisible by 5!");
isDivisible = true;
}
else if ((sum % 10 != 5) || (sum % 10 != 0))
{
Console.WriteLine("\nThe sum is not divisible by 5!");
isDivisible = false;
}
//depending on value of 'isDivisible', returns certain functions
if (isDivisible == true)
{
Console.WriteLine("This value is usable.");
Console.WriteLine("\n\nThe remaining usable values are: ");
for (int newVal = sum + 1; newVal <= 55; newVal++) // '+ 1' added to make sure 'sum' is not printed again
{
if ((newVal % 10 == 5) || (newVal % 10 == 0))
{
Console.WriteLine(newVal);
}
}
}
else if (isDivisible == false)
{
Console.WriteLine("This value is not usable.");
Console.WriteLine("\n\nThese values are considered usable: ");
for (int newVal = 0; newVal <= 55; newVal++)
{
if ((newVal % 10 == 5) || (newVal % 10 == 0))
{
Console.WriteLine(newVal);
}
}
}
Console.ReadLine();
}
I viewed some articles online, as well as the "Stack Overflow" post: Why compile error "Use of unassigned local variable"? . After learning that local variables are not initialized (and must be given a value), I set my bool value for "isDivisible" equal to true by default.
Question:
Is there a better way to define a local variable that is of Boolean value (at least in the case of the program I am trying to run here)?
Thanks!
Your condition in the else if is wrong, it's not the complement of the first condition, so it doesn't make sense. The correct complement would be:
else if ((sum % 10 != 5) && (sum % 10 != 0))
However, you don't need to use an else if at all, you can just use an else as you want to catch every case that is not caught by the first condition. That also means that you don't have to initialise the boolean variable, as the compiler can see that it always will be set by one of the code blocks:
bool isDivisible;
//checks if divisible by 5 and sets a value for 'isDivisible'
if ((sum % 10 == 5) || (sum % 10 == 0))
{
Console.WriteLine("\nThe sum is divisible by 5!");
isDivisible = true;
}
else
{
Console.WriteLine("\nThe sum is not divisible by 5!");
isDivisible = false;
}
Side note: Instead of (sum % 10 == 5) || (sum % 10 == 0) you could just use sum % 5 == 0.
Side note 2: You don't need to compare a boolean variable to true, you can just use it as a condition. Also, you don't need the else if there either. Instead of this:
if (isDivisible == true)
{
...
}
else if (isDivisible == false)
{
...
}
you can use:
if (isDivisible)
{
...
}
else
{
...
}
Comparison expressions in C# will return a boolean value indicating whether or not they are true. So you could simplify your initial assignment to:
bool isDivisible = ((sum % 10 == 5) || (sum % 10 == 0));
Instead of explicitly setting it to true or false. Then your variable would always be set.
This doesn't work for all cases. Sometimes, it is difficult to reduce the comparison operation to a simple expression. But, it is often a handy way to initialize bools.
I want to find whether a number is prime or not by limiting the number of iterations as much as possible.The following program was suggested in a blog.I can understand these parts of the code..
public static bool Isprime(long i)
{
if (i == 1)
{
return false;
}
else if (i < 4)
{
return true;
}
else if (i % 2 == 0)
{
return false;
}
else if (i < 9)
{
return true;
}
else if (i % 3 == 0)
{
return false;
}
But I don't understand why f is incremented by 6.
else
{
double r = Math.Floor(Math.Sqrt(i));
int f = 5;
while (f <= r)
{
if (i % f == 0) { return false; }
if (i % (f + 2) == 0) { return false; }
f = f + 6;
}
return true;
}
}
Because every prime number (except 2 and 3) is of the form 6k +/- 1
Every other number cannot be prime, because they are divisible by 2 or 3
Also, a few modifications to your method:
public static bool Isprime(long i)
{
if (i < 2)
{
return false;
}
else if (i < 4)
{
return true;
}
else if ((i & 1) == 0)
{
return false;
}
else if (i < 9)
{
return true;
}
else if (i % 3 == 0)
{
return false;
}
else
{
double r = Math.Floor(Math.Sqrt(i));
int f = 5;
while (f <= r)
{
if (i % f == 0) { return false; }
if (i % (f + 2) == 0) { return false; }
f = f + 6;
}
return true;
}
}
You didn't check for negative numbers
To check if a number is even, (i & 1) == 0 is more efficient. Unfortunately, there is no such trick for i % 3
Though a good answer has been accepted, and I've offered another answer previously, I offer a new method for ulong that does things slightly different that may help explain why the 6 is important. This uses a for loop rather than a while.
UPDATE: I have expanded upon this answer with a version that runs in parallel threads. See this CodeReview Link for the parallel version.
Edit: added quick elimination of many composites
public static bool IsPrime6(ulong number)
{
// Get the quick checks out of the way.
if (number < 2) { return false; }
// Dispense with multiples of 2 and 3.
if (number % 2 == 0) { return (number == 2); }
if (number % 3 == 0) { return (number == 3); }
// Another quick check to eliminate known composites.
// http://programmers.stackexchange.com/questions/120934/best-and-most-used-algorithm-for-finding-the-primality-of-given-positive-number/120963#120963
if (!( ((number - 1) % 6 == 0) || ((number + 1) % 6 == 0)) )
{
return false;
}
// Quick checks are over. Number is at least POSSIBLY prime.
// Must iterate to determine the absolute answer.
// We loop over 1/6 of the required possible factors to check,
// but since we check twice in each iteration, we are actually
// checking 1/3 of the possible divisors. This is an improvement
// over the typical naive test of odds only which tests 1/2
// of the factors.
// Though the whole number portion of the square root of ulong.MaxValue
// would fit in a uint, there is better performance inside the loop
// if we don't need to implicitly cast over and over a few million times.
ulong root = (ulong)(uint)Math.Sqrt(number);
// Corner Case: Math.Sqrt error for really HUGE ulong.
if (root == 0) root = (ulong)uint.MaxValue;
// Start at 5, which is (6k-1) where k=1.
// Increment the loop by 6, which is same as incrementing k by 1.
for (ulong factor = 5; factor <= root; factor += 6)
{
// Check (6k-1)
if (number % factor == 0) { return false; }
// Check (6k+1)
if (number % (factor + 2UL) == 0) { return false; }
}
return true;
}
This is based on math theorem that states every prime number > 3 can be represented as (6k+/-1). But that doesn't mean every number of the form (6k+/1) is a prime.
The correct converse would be that if you have a number that is not represented as (6k+/-1) then that number cannot be prime.
For later use with modulo operator, (6k-1) is equivalent to (6(k+1)+5).
Thus our intent is to start the loop at 5, i.e. the first occurrence of (6k-1) for k=1, do checks inside the loop for (6k-1) and (6k+1), and then increment by 6 for another iteration through the loop.
In short, iterating by adding 6 to the previous factor is the same as adding 1 to k.
Explanation of Ugly Explicit Casts
I took out the UL designators after further tests showed that for this algorithm they made little difference.
Tests
To run some tests, you could try:
const long Largest63bitPrime = 9223372036854775783L;
const ulong Largest64bitPrime = 18446744073709551557UL;
On my laptop, it take 13 seconds for the largest 63-bit prime, and 18 seconds for the largest 64-bit prime. Surprisingly, the version above is 1.5 seconds faster against (ulong)Largest63bitPrime than using my other answer's long specific version that employs a while.
Quick Elimination of Many Composites
Based on comments to the OP itself, I added a new check. It’s kind of difficult to find the worst case scenario, or best time-savings case here. I tested it against Largest64bitPrime + 6. Without the check, it was 14.2 microseconds compared to 1.1 microseconds with it. But's in now included so that the algorithm is considered complete.
See #Dennis_E's answer and explanation, which I gave +1. I offer 2 variations on his. There could be 100's of millions of implicit casts being done by these statements:
double r = Math.Floor(Math.Sqrt(i));
int f = 5;
while (f <= r)
The loop conditional implicitly cast f to a double repeatedly. That obscures where some performance can be degraded. While the whole number portion of the square root of long.MaxValue could fit in a uint, to boost performance you are better off keeping every as long. Now performance inside the loop will suffer from any implicit casts.
public static bool Isprime1(long number)
{
// Get the quick checks out of the way.
if (number < 2) { return false; }
// 2 and 3 are prime.
if (number < 4) { return true; }
// besides 2, any other even number, i.e. any other multiple of 2, is not prime.
if ((number % 2) == 0) { return false; }
// 5 and 7 are also prime.
if (number < 9) { return true; }
// multiples of 3 are not prime.
if (number % 3 == 0) { return false; }
// Quick checks are over. Must iterate to find the answer.
// Though the whole number portion of the square root of long.MaxValue
// would fit in a uint, there is better performance inside the loop
// if we don't need to implicitly cast over and over a few million times.
long root = (long)Math.Sqrt(number);
long factor = 5;
while (factor <= root)
{
if (number % factor == 0L) { return false; }
if (number % (factor + 2L) == 0L) { return false; }
factor = factor + 6L;
}
return true;
}
All the above extends the answer by #Dennis_E. Another variation would be:
public static bool Isprime2(long number)
{
// Get the quick checks out of the way.
if (number < 2) { return false; }
// 2, 3, 5, & 7 are prime.
if ((new long[] { 2L, 3L, 5L, 7L }).Contains(number)) { return true; }
// any other multiples of 2 are not prime.
if ((number % 2) == 0) { return false; }
// any other multiples of 3 are not prime.
if (number % 3 == 0) { return false; }
// Quick checks are over. Must iterate to find the answer.
// Though the whole number portion of the square root of long.MaxValue
// would fit in a uint, there is better performance inside the loop
// if we don't need to implicitly cast over and over a few million times.
long root = (long)Math.Sqrt(number);
long factor = 5;
while (factor <= root)
{
if (number % factor == 0L) { return false; }
if (number % (factor + 2L) == 0L) { return false; }
factor = factor + 6L;
}
return true;
}
public class Prime {
public static void main(String[] args) {
Scanner get=new Scanner(System.in);
int n;
System.out.println("Enter a number to find its primality");
n=get.nextInt();
System.out.println(n+" isPRime? "+isPrime(Math.ceil(Math.sqrt(n)),n));
}
private static boolean isPrime(double n,int k){
boolean isPrim=true;
int p=(int)n;
for(int i=2;i<=p;i++){
boolean iprime=false;
for(int j=2;j<i/2;j++){
if(i%j==0){
iprime=true;
break;
}
}
if(!iprime && k>i){
if(k%i==0){
isPrim=false;
return isPrim;
}
}
}
return isPrim;
}
}
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.
In my program, I think my count variable is not holding the value. What do I do so that it can hold? here`s my code.
static void Main(string[] args)
{
double a;
double count = 0;
Console.WriteLine("Enter the Numbers : ");
for (double i = 1; i <= 10; i++)
{
a = Convert.ToDouble(Console.ReadLine());
if (a % 2 != 0 || a % 3 != 0 || a % 5 != 0)
{
count = count++;
}
//else
//{
// }
Console.ReadLine();
}
Console.WriteLine("The Numbers That Are divisible by 2,3,5 are : " + count);
Console.ReadLine();
}
Your mistake is the line count = count++;. This does not increase count by one. You need to use just count++;.
The expression count++ will increment the value of count by one and then return as the expression's value the original value of count. In this case the increment of count++ happens before the assignment, so count is first incremented by one, but then you assign the value of count++, that is, the original value, to count again, so it does not increase at all.
Your program lists numbers that are not divisible by any of those numbers. If you want to count numbers which aren't divisible by all of them then you need to use if (a % 2 != 0 && a % 3 != 0 && a % 5 != 0) instead. I would also suggest using integers instead of doubles if possible.
Finally, your print statement says numbers that are divisible by 2,3,5, but count is the number of numbers which are not divisible by those numbers.
Edit: Are you entering 10 numbers each time you test? I'm not sure what kind of result you will get if you give a blank input.
Not to add to what jk and David Kanarek said in their answers or what the others the comments on those answers, As pointed out by jk use count+1 instead of count ++ , also a few notes:
1) Your using console.Readline() twice in the loop, so the user will enter 20 inputs but only 10 will be read..
2) Just alittle extra thought on Anton's comment, in your if clause , if you use || your trying to catch any of the conditions being true, in other words:
// a=2
if (a % 2 != 0 || a % 3 != 0 || a % 5 != 0) // False || True || True = True
{
count = count + 1 ;// count will increase
}
on the other hand, using && :
// a=2
if (a % 2 != 0 && a % 3 != 0 && a % 5 != 0) // False && True && True = false
{
count = count + 1 ; //count will not increase
}
A useful Link explaining operators