Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I got case 1-3 working, but I cant get 4-7 working or don't know how I would type it or approach it.
As you can see in number 4 I programmed so when I run the program and press 4 it should run case 4 count down to 10 but skip 7 why wont it work? Also cant figure out how to do 5-7.
I haven't learned that far yet if could help me and also explain how your code works out the problem for me it would be really appropriated.
namespace WhileLoopExercises
{
class Program
{
static void Main(string[] args)
{
int selection = 0;
while (selection != 9)
{
Console.Clear();
Console.WriteLine("\n\n Menu:\n");
Console.WriteLine("\t 1. Display 10 stars( one per line)");
Console.WriteLine("\t 2. Request a value 1 to 50 from user, then display");
Console.WriteLine("\t 3. Display 10 rows of 3 stars");
Console.WriteLine("\t 4. Add all values between 1 to 10 except 7");
Console.WriteLine("\t 5. Display all the even numbers between 10 and 100");
Console.WriteLine("\t 6. Add all the odd numbers bewteen 10 and 100");
Console.WriteLine("\t 7. Generate 6 random numbers ranging from 1 to 49");
Console.WriteLine("\t 8. Exit Apllication");
Console.Write("Enter your selection: ");
selection = int.Parse(Console.ReadLine());
switch (selection)
{
case 1:
{
int counter = 1;
while (counter <= 10)
{
Console.WriteLine("*");
counter++;
}
}
break;
case 2:
{
Console.Write("Enter integer 0-50 : ");
int N = int.Parse(Console.ReadLine());
int counter = 1;
while (counter <= N)
{
Console.Write("*");
counter++;
}
}
break;
case 3:
{
int counter = 1;
while (counter <= 10)
{
Console.WriteLine("***");
counter++;
}
}
break;
case 4:
{
int counter = 1;
while (counter <= 10)
{
if (counter == 7)
{
counter++;
}
}
}
break;
case 5:
{
int counter = 1;
while (counter <= 100)
{
}
}
break;
case 6:
{
}
break;
case 7:
{
}
break;
}// end of switch
//pause
Console.WriteLine("\n\nHit any key to coutinue");
Console.ReadKey();
}
}
}
}
We can't do your homework for you on stack overflow. However, we can point out your logical issues.
Looking at case four, we see
case 4:
{
int counter = 1;
while (counter <= 10)
{
if (counter == 7)
{
counter++;
}
}
}
Walk through the problem now. We start with a counter of 1, and while it is less than or equal to 10, we enter your if statement.
Your if statement says "If my counter is equal to seven, then increment (increase) the counter by one." However, your counter enters at 1, and there is no other logic defining the counter's behavior, so nothing happens! This loop then goes on forever (Oops!). With this in mind, try solving again.
Here are some suggestions for number 4, without just writing the solution:
Your counter starts at 1, the loop continues while counter <= 10, but you only increment it if counter == 7. Does that seem like a problem?
You're doing something when counter == 7, but in fact "7" is the only time you don't want to be doing anything.
You need to create another variable to store your "sum" in, then add each value to it.
Case 4 won't work as is since it will only increment when counter is 7. So it stays infinitely at 1. This should work (without the line numbers at the start - they're for a section below):
1 int counter = 1;
2 int sum = 0; // Need to maintain sum
3 while (counter <= 10) { // Do all numbers 1 thru 10
4 if (counter != 7) // Skip 7
5 sum += counter;
6 counter++;
7 }
8 Console.Write (sum);
A similar approach can be taken with all the other cases. All you have to do is figure out exactly what it's asking and map that to code. Try something to see if it works and, if not, run the code through your head to see where it's going wrong. During the learning process, being able to emulate a computer in your head is a valuable skill to learn.
It's often advantageous to sit down with a pencil and paper and run each line in turn (with line numbers matching those in the code above):
line | counter | sum | comment
-----+---------+-----+--------
1 | 1 | ? |
2 | | 0 |
3 | | | 1 <= 10, will enter 'while'
4 | | | 1 != 7, will enter 'if'
5 | | 1 |
6 | 2 | |
7 | | | return to while loop start
3 | | | 2 <= 10, will enter 'while'
:
and so on.
Another example of mapping the requirements to code comes from case 6: Add all the odd numbers between 10 and 100. This can be achieved thus:
the first odd number > 10 is 11.
each subsequent odd number is two more than the previous.
you loop until you're greater than 100.
That would lead to the following pseudo-code:
set sum to 0
set num to 11
while num is less than or equal to 100:
add num to sum
add 2 to num
output sum
I'll leave converting that to a real language as an exercise for the reader.
Linq lets you express code in much more compact and readable way.
case 4:
Console.Write (Enumerable.Range(1,100).Where(v => v != 42).Sum());
If you need more basic code consider for instead of while as it represent iteration over ranges in more idiomatic way (and continue is likely what you are expected to use for 4 to skip numbers):
case 4:
{
var sum = 0;
for(var i = 1; i <= 20; i++)
{
if (i != 3)
continue;
sum += 0;
}
break;
}
Related
Prime Number Generator Code
Do know that this question should be quite basic but i have spent hours trying to figure out why my code is stuck in the loop as below. Have added a Console.WriteLine($"{counttemp} , {count1} "); in the if loop to check the 2 numbers and seems like it is not breaking out of the if condition when the condition is true
this is the console output for the writeline in the if loop
5 , 5
6 , 2
7 , 7
8 , 2
9 , 3
10 , 2
11 , 11
12 , 2
13 , 13
14 , 2
15 , 3
16 , 2
17 , 17
18 , 2
19 , 19
Problematic Loop??
for (count1 = 2; count1 <= counttemp ; ++count1)
{
if(counttemp % count1 == 0)
{
Console.WriteLine($"{counttemp} , {count1} ");
Console.ReadKey();
primetest1 = 0;
break;
}
}
full code sequence
static void Main(string[] args)
{
int prime1 = 10000, count1, primetest1, counttemp;
for (counttemp = 5; counttemp <= prime1; counttemp++)
{
primetest1 = 1;
for (count1 = 2; count1 <= counttemp ; ++count1)
{
if(counttemp % count1 == 0)
{
Console.WriteLine($"{counttemp} , {count1} ");
Console.ReadKey();
primetest1 = 0;
break;
}
}
if (primetest1 == 1)
{
Console.Write($"{counttemp}");
}
}
}
You're almost there. The problem is that you're checking if your candidate number is a prime by getting the remainder when divided by each number up to and including the number itself.
I think you'll find that N is a factor of N for all values of N. To fix this, you should only be checking up to but excluding the number.
And, as an aside, you don't really need to check all the way up to N - 1. You only need to go to the square root of N, adjusted up to the nearest integer. That's because, if it has a factor above the square root, you would already have found a factor below it.
Consider 24 as an example. It has 6, 8, and 12 as factors above the square root, but the matching values below the square root are 4, 3, and 2 respectively.
And there's a another trick you can use by realising that if a number is a multiple of a non-prime, it's also a multiple of every prime factor of that non-prime. In other words, every multiple of 12 is also a multiple of 2 and 3.
So you only need to check prime numbers up to the square root, to see if there's a factor. And prime numbers, other than two or three, are guaranteed to be of the form 6x-1 or 6x+1, so it's quite easy to filter out a large chunk of candidates very quickly, by checking only for those values.
In other words, check two and three as special cases. Then start at 5 and alternately add 2 and 4: 5, 7, 11, 13, 17, 19, .... Not every number in that set is prime (e.g, 25) every prime is guaranteed to be in that set.
You can check out an earlier answer of mine for more detail on why this is so, and how to do this sequence efficiently.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
i solved an assignment question on my own but i seems not to be able to print an else statement successfully even though the code works.
The questions is below,
Create a program that prompts the user for the first number. Show on the screen which number was chosen and if the
Number is greater than 10 then show your predecessors until you reach number 10.
My solution is below,
Console.WriteLine("Enter interger please: ");
int num = int.Parse(Console.ReadLine());
Console.WriteLine();
for (int num3 = num; 10 <= num3; num3-- )
{
if (num > 10)
{
Console.WriteLine(num3);
}
else
{
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
}
Well it's normal that in doesn't enter the else statement. You're doing if (num > 10) and num is the value entered by the user which never changes during the process. So if num = 15 you're always doing is 15 > 10.
Then only moment the else statement is gonna print is if the number entered is 10.
And the moment num is smaller than 10, you'll never get in the for loop so the number will never be smaller than 0 inside the loop so that line won't make sense even if it's played
Console.WriteLine("The integer entered is less than zero and cannot be used in code ");
Cause like i said if this line is printed that means the value in num was 10 which is not less than zero.
You could change it for something like this
if(num < 10)
{
Console.WriteLine("It's smaller than 10");
}
for(int num3 = num; 10 <= num3; num3--)
{
Console.WriteLine(num3);
}
You're decrementing "num3" on the for loop, but you're validating if "num" is greater than 10 which, by entering the loop in the first place, will always be true.
Change to:
if (num3 > 10)
{
Console.WriteLine(num3);
}
Are you able to provide the question?
The code you have written seems a little meaningless.
Firstly, the for loop will only run if you enter an integer >= 10
Rewriting your code:
Console.WriteLine("Please enter a positive integer: ");
var args = Console.ReadLine();
if (int.TryParse(args, out int num))
{
if (num < 0)
Console.WriteLine('Must enter a positive integer!');
for (var i = num; i >= 10; i-- )
{
//this only runs if the integer entered is >= 10
if (num > 10)
{
Console.WriteLine(i);
}
}
}
else
{
Console.WriteLine("A non-integer was entered!");
}
This is what I have so far:
int num = 12345;
int length = Math.Floor(Math.Log10(num)+1);
Console.WriteLine(length);
Console.ReadKey();
The output should be 5.
This is obviously giving me errors, but I really don't know another way of how to do it since the instructions are so clear to not use ToString.
Any help or guidance would be appriciated. Thanks.
There are two ways to go about this: The really lazy easy way, and a slightly less lazy but simpler-to-understand way.
Here's the easy way. It's almost what you did, but with a few tweaks to handle the zero corner-case, and the requisite cast:
int length = number > 0 ? (int)Math.Floor(Math.Log10(number)) + 1 : 1;
The slightly less lazy solution is repeated division by ten; to know how many digits there are, you just keep dividing by ten until you run out of them:
int length = 0;
while (number > 0) {
length++;
number /= 10;
}
if (length < 1) length = 1;
The last "less than one" check is because you obviously can't have a number with no digits at all in it.
As one of the commenters noted, this only works for nonnegative integers. (But then the "length" of a negative integer is an interesting meta-question in and of itself; should you include the sign as part of the length, or is it merely the number of digits?) If you want it to work for negative values (or fractions), you'll have to convert them to positive values first, and then potentially add one more position for the sign, depending on what you're trying to compute.
Anyway, there ya go. Nice and easy.
The length is 1+⌊log10max(1,|x|)⌋. So you can implement it like:
int length = 1+Math.Floor(Math.Log10(Math.Max(1,Math.Abs(num))));
Examples in the csharp console:
csharp> for(int i = 0; i < 15; i++) {
> Console.WriteLine("{0}: {1}",i,1+Math.Floor(Math.Log10(Math.Max(1,Math.Abs(i)))));
> }
0: 1
1: 1
2: 1
3: 1
4: 1
5: 1
6: 1
7: 1
8: 1
9: 1
10: 2
11: 2
12: 2
13: 2
14: 2
csharp> for(int i = 0; i > -15; i--) {
> Console.WriteLine("{0}: {1}",i,1+Math.Floor(Math.Log10(Math.Max(1,Math.Abs(i)))));
> }
0: 1
-1: 1
-2: 1
-3: 1
-4: 1
-5: 1
-6: 1
-7: 1
-8: 1
-9: 1
-10: 2
-11: 2
-12: 2
-13: 2
-14: 2
You can divide the number by 10 (i.e. shift the decimal separator) until all the digits are on the right side of the decimal separator:
public static int GetNumDigitsWithoutToString(int forInput)
{
if (forInput == 0) return 1; // guard clause to prevent divide by zero error.
int numDigits = 0;
var x = (decimal) forInput;
while (x >= 1)
{
numDigits++;
x = x / 10;
}
return numDigits;
}
IMO the easiest one to understand would be :
int num = 12345;
int counter = 1; // start counter with one because you'll automatically "remove" one sign
while ( ( num /= 10 ) != 0 ) counter++;
//Console.WriteLine(counter) >> 5;
This will work with negatives as well.
online example
I created a program to create a polynomial. However, I cannot make it to display the exponent in the correct manner.
For example, if I enter [1,2,3] in my array to create my polynomial I get back the polynomial: 1 + 2x + 3x^(2). What I want to get back is: 1x^(2) + 2x + 3. Notice that the numbers in my array are still in the same order. The only thing that changed was that the exponent and power changed to start from the left side (the highest degree begins from the left). I need help doing this part.
Here is my code for the loop that was sorting it:
\
Thanks in advance!
Just initiate i to n-1 and substract in each iteration
public void printPoly1(int[] poly, int n)
{
for (int i = n-1; i >= 0; i--)
{
Console.Write(poly[i]);
if (i != 0)
{
Console.Write("x^" + i + " + ");
}
}
Console.WriteLine("\n");
}
Change this if part
if (i != 0)
{
Console.Write("x^" + i);
}
To this
if ((n - 1 - i) != 0)
{
Console.Write("x^" + (n - 1 - i));
}
Because the power should start from end of loop to start (like inverse loop). but you are iterating from start to end (normal loop). So subtract counter (i) from n - 1.
If you still didnt understand then look here. the first line is counter in loop and should start from 0 to 6.
0 1 2 3 4 5 6 // normal
6-0 6-1 6-2 6-3 6-4 6-5 6-6 // do subtract
6 5 4 3 2 1 0 // inverse
I'm trying to refactor this algorithm to make it faster. What would be the first refactoring here for speed?
public int GetHowManyFactors(int numberToCheck)
{
// we know 1 is a factor and the numberToCheck
int factorCount = 2;
// start from 2 as we know 1 is a factor, and less than as numberToCheck is a factor
for (int i = 2; i < numberToCheck; i++)
{
if (numberToCheck % i == 0)
factorCount++;
}
return factorCount;
}
The first optimization you could make is that you only need to check up to the square root of the number. This is because factors come in pairs where one is less than the square root and the other is greater.
One exception to this is if n is an exact square then its square root is a factor of n but not part of a pair.
For example if your number is 30 the factors are in these pairs:
1 x 30
2 x 15
3 x 10
5 x 6
So you don't need to check any numbers higher than 5 because all the other factors can already be deduced to exist once you find the corresponding small factor in the pair.
Here is one way to do it in C#:
public int GetFactorCount(int numberToCheck)
{
int factorCount = 0;
int sqrt = (int)Math.Ceiling(Math.Sqrt(numberToCheck));
// Start from 1 as we want our method to also work when numberToCheck is 0 or 1.
for (int i = 1; i < sqrt; i++)
{
if (numberToCheck % i == 0)
{
factorCount += 2; // We found a pair of factors.
}
}
// Check if our number is an exact square.
if (sqrt * sqrt == numberToCheck)
{
factorCount++;
}
return factorCount;
}
There are other approaches you could use that are faster but you might find that this is already fast enough for your needs, especially if you only need it to work with 32-bit integers.
Reducing the bound of how high you have to go as you could knowingly stop at the square root of the number, though this does carry the caution of picking out squares that would have the odd number of factors, but it does help reduce how often the loop has to be executed.
Looks like there is a lengthy discussion about this exact topic here: Algorithm to calculate the number of divisors of a given number
Hope this helps
The first thing to notice is that it suffices to find all of the prime factors. Once you have these it's easy to find the number of total divisors: for each prime, add 1 to the number of times it appears and multiply these together. So for 12 = 2 * 2 * 3 you have (2 + 1) * (1 + 1) = 3 * 2 = 6 factors.
The next thing follows from the first: when you find a factor, divide it out so that the resulting number is smaller. When you combine this with the fact that you need only check to the square root of the current number this is a huge improvement. For example, consider N = 10714293844487412. Naively it would take N steps. Checking up to its square root takes sqrt(N) or about 100 million steps. But since the factors 2, 2, 3, and 953 are discovered early on you actually only need to check to one million -- a 100x improvement!
Another improvement: you don't need to check every number to see if it divides your number, just the primes. If it's more convenient you can use 2 and the odd numbers, or 2, 3, and the numbers 6n-1 and 6n+1 (a basic wheel sieve).
Here's another nice improvement. If you can quickly determine whether a number is prime, you can reduce the need for division even further. Suppose, after removing small factors, you have 120528291333090808192969. Even checking up to its square root will take a long time -- 300 billion steps. But a Miller-Rabin test (very fast -- maybe 10 to 20 nanoseconds) will show that this number is composite. How does this help? It means that if you check up to its cube root and find no factors, then there are exactly two primes left. If the number is a square, its factors are prime; if the number is not a square, the numbers are distinct primes. This means you can multiply your 'running total' by 3 or 4, respectively, to get the final answer -- even without knowing the factors! This can make more of a difference than you'd guess: the number of steps needed drops from 300 billion to just 50 million, a 6000-fold improvement!
The only trouble with the above is that Miller-Rabin can only prove that numbers are composite; if it's given a prime it can't prove that the number is prime. In that case you may wish to write a primality-proving function to spare yourself the effort of factoring to the square root of the number. (Alternately, you could just do a few more Miller-Rabin tests, if you would be satisfied with high confidence that your answer is correct rather than a proof that it is. If a number passes 15 tests then it's composite with probability less than 1 in a billion.)
You can limit the upper limit of your FOR loop to numberToCheck / 2
Start your loop counter at 2 (if your number is even) or 3 (for odd values). This should allow you to check every other number dropping your loop count by another 50%.
public int GetHowManyFactors(int numberToCheck)
{
// we know 1 is a factor and the numberToCheck
int factorCount = 2;
int i = 2 + ( numberToCheck % 2 ); //start at 2 (or 3 if numberToCheck is odd)
for( ; i < numberToCheck / 2; i+=2)
{
if (numberToCheck % i == 0)
factorCount++;
}
return factorCount;
}
Well if you are going to use this function a lot you can use modified algorithm of Eratosthenes http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes and store answars for a interval 1 to Max in array. It will run IntializeArray() once and after it will return answers in 0(1).
const int Max =1000000;
int arr [] = new int [Max+1];
public void InitializeArray()
{
for(int i=1;i<=Max;++i)
arr[i]=1;//1 is factor for everyone
for(int i=2;i<=Max;++i)
for(int j=i;i<=Max;i+=j)
++arr[j];
}
public int GetHowManyFactors(int numberToCheck)
{
return arr[numberToCheck];
}
But if you are not going to use this function a lot I think best solution is to check unitll square root.
Note: I have corrected my code!
An easy to implement algorithm that will bring you much farther than trial division is Pollard Rho
Here is a Java implementation, that should be easy to adapt to C#: http://www.cs.princeton.edu/introcs/78crypto/PollardRho.java.html
https://codility.com/demo/results/demoAAW2WH-MGF/
public int solution(int n) {
var counter = 0;
if (n == 1) return 1;
counter = 2; //1 and itself
int sqrtPoint = (Int32)(Math.Truncate(Math.Sqrt(n)));
for (int i = 2; i <= sqrtPoint; i++)
{
if (n % i == 0)
{
counter += 2; // We found a pair of factors.
}
}
// Check if our number is an exact square.
if (sqrtPoint * sqrtPoint == n)
{
counter -=1;
}
return counter;
}
Codility Python 100 %
Here is solution in python with little explanation-
def solution(N):
"""
Problem Statement can be found here-
https://app.codility.com/demo/results/trainingJNNRF6-VG4/
Codility 100%
Idea is count decedent factor in single travers. ie. if 24 is divisible by 4 then it is also divisible by 8
Traverse only up to square root of number ie. in case of 24, 4*4 < 24 but 5*5!<24 so loop through only i*i<N
"""
print(N)
count = 0
i = 1
while i * i <= N:
if N % i == 0:
print()
print("Divisible by " + str(i))
if i * i == N:
count += 1
print("Count increase by one " + str(count))
else:
count += 2
print("Also divisible by " + str(int(N / i)))
print("Count increase by two count " + str(count))
i += 1
return count
Example by run-
if __name__ == '__main__':
# result = solution(24)
# result = solution(35)
result = solution(1)
print("")
print("Solution " + str(result))
"""
Example1-
24
Divisible by 1
Also divisible by 24
Count increase by two count 2
Divisible by 2
Also divisible by 12
Count increase by two count 4
Divisible by 3
Also divisible by 8
Count increase by two count 6
Divisible by 4
Also divisible by 6
Count increase by two count 8
Solution 8
Example2-
35
Divisible by 1
Also divisible by 35
Count increase by two count 2
Divisible by 5
Also divisible by 7
Count increase by two count 4
Solution 4
Example3-
1
Divisible by 1
Count increase by one 1
Solution 1
"""
Github link
I got pretty good results with complexity of O(sqrt(N)).
if (N == 1) return 1;
int divisors = 0;
int max = N;
for (int div = 1; div < max; div++) {
if (N % div == 0) {
divisors++;
if (div != N/div) {
divisors++;
}
}
if (N/div < max) {
max = N/div;
}
}
return divisors;
Python Implementation
Score 100% https://app.codility.com/demo/results/trainingJ78AK2-DZ5/
import math;
def solution(N):
# write your code in Python 3.6
NumberFactor=2; #one and the number itself
if(N==1):
return 1;
if(N==2):
return 2;
squareN=int(math.sqrt(N)) +1;
#print(squareN)
for elem in range (2,squareN):
if(N%elem==0):
NumberFactor+=2;
if( (squareN-1) * (squareN-1) ==N):
NumberFactor-=1;
return NumberFactor