C#. I would like to compare a random number to a guess.
If the guess is 3 more or 3 less than the random number , the program should show the statement
Console.WriteLine("Almost right");
Can I write like this?
If (randomnumber < guess+3 | randomnumber> guess-3);
Console.Writeln ("Almost right")
I am not using array.
Is there a more efficient way to write the code?
You are on the right track.
When you write code here, you can and should write it as code, read the markdown spec or get accustomed to the editor here at stackoverflow. code looks like:
If (randomnumber < guess+3 | randomnumber> guess-3); Console.Writeln ("Almost right")
You should then write real code because your code is more c# like pseudo code. Correctly you must write:
if (randomnumber < guess+3 || randomnumber> guess-3) {
Console.Writeln ("Almost right");
}
Check the logical operators in C#, its || not |
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators
Performance wise this is fine you could write a specific method like
bool IsRoughly (x, y) {
return x < y + 3 || y < x + 3;
}
This puts the esence of your logic more into light. Finally you have to think about the corner cases: Is 1 really almost the maximum value of an int? Probably not.
With C# 9 you can do in easy readable way. These are just alternative ways do to the the same thing in bit different way
if (randomnumber is < (guess+3) or randomnumber is > (guess-3))
{
Console.WriteLine("Almost right");
}
Another alternative way is to use
if(Enumerable.Range(guess - 2, guess + 2).Contains(randomnumber))
Related
I have tried to write a code for Fermat primality test, but apparently failed.
So if I understood well: if p is prime then ((a^p)-a)%p=0 where p%a!=0.
My code seems to be OK, therefore most likely I misunderstood the basics. What am I missing here?
private bool IsPrime(int candidate)
{
//checking if candidate = 0 || 1 || 2
int a = candidate + 1; //candidate can't be divisor of candidate+1
if ((Math.Pow(a, candidate) - a) % candidate == 0) return true;
return false;
}
Reading the wikipedia article on the Fermat primality test, You must choose an a that is less than the candidate you are testing, not more.
Furthermore, as MattW commented, testing only a single a won't give you a conclusive answer as to whether the candidate is prime. You must test many possible as before you can decide that a number is probably prime. And even then, some numbers may appear to be prime but actually be composite.
Your basic algorithm is correct, though you will have to use a larger data type than int if you want to do this for non-trivial numbers.
You should not implement the modular exponentiation in the way that you did, because the intermediate result is huge. Here is the square-and-multiply algorithm for modular exponentiation:
function powerMod(b, e, m)
x := 1
while e > 0
if e%2 == 1
x, e := (x*b)%m, e-1
else b, e := (b*b)%m, e//2
return x
As an example, 437^13 (mod 1741) = 819. If you use the algorithm shown above, no intermediate result will be greater than 1740 * 1740 = 3027600. But if you perform the exponentiation first, the intermediate result of 437^13 is 21196232792890476235164446315006597, which you probably want to avoid.
Even with all of that, the Fermat test is imperfect. There are some composite numbers, the Carmichael numbers, that will always report prime no matter what witness you choose. Look for the Miller-Rabin test if you want something that will work better. I modestly recommend this essay on Programming with Prime Numbers at my blog.
You are dealing with very large numbers, and trying to store them in doubles, which is only 64 bits.
The double will do the best it can to hold your number, but you are going to loose some accuracy.
An alternative approach:
Remember that the mod operator can be applied multiple times, and still give the same result.
So, to avoid getting massive numbers you could apply the mod operator during the calculation of your power.
Something like:
private bool IsPrime(int candidate)
{
//checking if candidate = 0 || 1 || 2
int a = candidate - 1; //candidate can't be divisor of candidate - 1
int result = 1;
for(int i = 0; i < candidate; i++)
{
result = result * a;
//Notice that without the following line,
//this method is essentially the same as your own.
//All this line does is keeps the numbers small and manageable.
result = result % candidate;
}
result -= a;
return result == 0;
}
I am writing a Sudoku application and am currently working on the game generation algorithm. I managed to figure out how to quickly generate a solution (not solve). I am stumped on how to remove some of the numbers to actually make it into a puzzle, though. My first inclination was to randomly remove a certain number of cells based on the difficulty, but that is not the correct algorithm, because it often renders a puzzle that is unsolvable or has multiple solutions. It also might generate puzzles that don't reflect the requested difficulty.
Here is the code that I have so far. I removed most of the irrelevant code, but if you would like to see something that isn't implemented but used below, please let me know. I can also provide my attempt at the Puzzlefy method if you would like, but I opted out of immediately posting it since it's blatantly wrong (even though it "works").
using System;
using System.Collections.Generic;
using System.Linq;
namespace Sudoku
{
public class Game
{
public enum Difficulty
{
VeryEasy,
Easy,
Medium,
Difficult,
Evil
}
private readonly int?[,] _currentItems = new int?[9,9];
private readonly int?[,] _solution = new int?[9,9];
private readonly int?[,] _startingItems = new int?[9,9];
private readonly Difficulty _difficulty;
public Game(Difficulty difficulty)
{
_difficulty = difficulty;
GenerateSolution();
Puzzlefy();
}
private void GenerateSolution()
{
var random = new Random();
var availableNumbers = new Stack<List<int?>>(81);
var x = 0;
var y = 0;
availableNumbers.Push(AllowableNumbers(_solution, 0, 0).ToList());
while (x < 9 && y < 9)
{
var currentAvailableNumbers = AllowableNumbers(_solution, x, y).ToList();
availableNumbers.Push(currentAvailableNumbers);
// back trace if the board is in an invalid state
while (currentAvailableNumbers.Count == 0)
{
_solution[x, y] = null;
availableNumbers.Pop();
currentAvailableNumbers = availableNumbers.Peek();
x -= y >= 1 ? 0 : 1;
y = y >= 1 ? y - 1 : 8;
}
var index = random.Next(currentAvailableNumbers.Count);
_solution[x, y] = currentAvailableNumbers[index];
currentAvailableNumbers.RemoveAt(index);
x += y < 8 ? 0 : 1;
y = y < 8 ? y + 1 : 0;
}
}
private void Puzzlefy()
{
CopyCells(_solution, _startingItems);
// remove some stuff from _startingItems
CopyCells(_startingItems, _currentItems);
}
}
}
I am not looking for code, rather an algorithm. How would I go about removing the numbers from the solution to make it into a puzzle?
Here is a paper on sudoku generation
I think that you will need a sudoku solver that will also count the number of solutions available, then substract numbers in such a way that there is always only one available solution.
You could apply the same method to adding numbers to the grid, then check the number of possible solution and keep adding when the number of solution is greater than 1 and backtracking when the number of solutions is 0
There is no "easy" way to remove clues from a completed Sudoku grid as the removal process is not linear.
After each removal of a cell or clue you need to check if the Sudoku only has a unique solution.
To check this you need to run a solver that can count all possible solutions (you can stop it after 2 possibilities are found to save time).
The two most popular algorithm used both for solving a Sudoku, counting all the Sudoku solutions and removing cells are backtracking algorithms and dancing links algorithms.
This article explains really well how the dancing links algorithm can be used in Sudokus:
http://garethrees.org/2007/06/10/zendoku-generation/#section-2
Here is another description of a dancing link algorithm in Sudokus written in JavaScript:
http://www.sudokubum.com/documentation.html
And here is the full paper about dancing links algorithms in general:
http://lanl.arxiv.org/pdf/cs/0011047
I have the following (simplified) conditions that need to be validated for a form I am writing:
a > b
a > c
a > d
b > c
b > d
c > d
Graphically, this can be seen as:
The user has freedom to enter values for a, b, c, and d, which is why they need to be validated to make sure they obey those rules. The problem I am having is writing something that clearly and efficiently evaluates each statement. Of course, the most obvious way would be to evaluate each statement separately as an if-statement. Unfortunately, this takes up a lot of lines of code, and I'd rather avoid cluttering up the method with a bunch of if-blocks that do almost the same thing. I did come up with the following nested for-loop solution, using arrays. I built an array of the values, and looped over it twice (demonstrated in Python-like pseudo-code):
A = [a, b, c, d]
for i in range(3):
for j in range(i, 4):
if i > j and A[i] >= A[j]:
print("A[i] must be less than A[j]")
else if i < j and A[i] <= A[j]:
print("A[j] must be greater than A[i]")
The problem I have with this solution is it is hard to read and understand - the solution just isn't clear.
I have this nagging feeling that there is a better, clearer answer out there, but I can't think of it for the life of me. This isn't homework or anything - I am actually working on a project and this problem (or subtle variations of it) arose more than once, so I would like to make a reusable solution that is clear and efficient. Any input would be appreciated. Thanks!
if a > b > c > d:
do ok
else:
for x in range(3):
if A[i] <= A[i+1]:
print A[i], ' not greater than', A[i+1]
If you can't assume transitivity of comparison:
from itertools import combinations
for x, y in combinations(A, 2):
if x <= y:
print("{} not greater than {}".format(x, y))
Otherwise, f p's solution is optimal.
You could create delegates for each check and add these to an array. Create appropriate delegates, like bool LargerCheck(a,b, string error) and add them to an array which you can loop through...
A lot of work though and more complex, if more readable. I think I would just hide the messy checks in a single validationblock and have a easily readable single check in the normal code. Something like this;
// Simple readable check in normal code
if (!ValidationOk(a,b,c,d,response)
{
ShowResponse(response);
Break;
}
// messy routine
private bool ValidationOk(a,b,c,d,List<string> valerrors)
{
valerrors.Clear();
if (a<b) valerrors.Add("a < b");
if (a<c) valerrors.Add("a < c");
....
return valerrors.Count == 0;
}
I manually adjust the thread count:
if (items.Count == 0) { threads = 0; }
else if (items.Count < 1 * hundred) { threads = 1; }
else if (items.Count < 3 * hundred) { threads = 2; }
else if (items.Count < 5 * hundred) { threads = 4; }
else if (items.Count < 10 * hundred) { threads = 8; }
else if (items.Count < 20 * hundred) { threads = 11; }
else if (items.Count < 30 * hundred) { threads = 15; }
else if (items.Count < 50 * hundred) { threads = 30; }
else threads = 40;
I need a function that returns the necessary/optimized thread count.
Ok, now forget above. I need a graph curve to plot. I give the coords, function plots the curve. Imagine the point(0,0) and point(5,5) -in (x,y) form. It should be straight line. So then I can measure x for y=3.
What happens if I give the points (0,0), (2,3), (8,10), (15,30) and (30,50). It will be a curve like thing. Now can I calculate x for given y or vice versa?
I think you get the idea. Should I use MathLab or could it be done in C#?
You're looking for curve fitting, or the derivation of a function describing a curve from a set of data points. If you're looking to do this once, from a constant set of data, Matlab would do the job just fine. If you want to do this dynamically, there are libraries and algorithms out there.
Review the Wikipedia article on linear regression. The least squares approach mentioned in that article is pretty common. Look around, and you'll find libraries and code samples using that approach.
You can probably make that run faster by reordering the tests (and using nested if). But that's not a smooth function, there's not likely to be any simpler description.
Or are you trying to find a smooth function that passes near those points?
You could use a linear regression; you would get something like this:
So I would probably encode it in C# like this:
int threads = (int) Math.Ceiling(0.0056*items.Count + 0.5);
I used Math.Ceiling to ensure that you don’t get 0 when the input isn’t 0. Of course, this function gives you 1 even if the input is 0; if that matters, you can always catch that as a special case, or use Math.Round instead.
However, this means the number of threads will go up continuously. It will not level out at 40. If that’s what you want, you might need to research different kinds of regression.
I am have difficulties solving this problem:
For a positive number n, define C(n)
as the number of the integers x, for
which 1 < x < n and x^3 = 1 mod n.
When n=91, there are 8 possible values
for x, namely : 9, 16, 22, 29, 53, 74,
79, 81. Thus, C(91)=8.
Find the sum of the positive numbers
n <= 10^11 for which C(n) = 242.
My Code:
double intCount2 = 91;
double intHolder = 0;
for (int i = 0; i <= intCount2; i++)
{
if ((Math.Pow(i, 3) - 1) % intCount2 == 0)
{
if ((Math.Pow(i, 3) - 1) != 0)
{
Console.WriteLine(i);
intHolder += i;
}
}
}
Console.WriteLine("Answer = " + intHolder);
Console.ReadLine();
This works for 91 but when I put in any large number with a lot of 0's, it gives me a lot of answers I know are false. I think this is because it is so close to 0 that it just rounds to 0. Is there any way to see if something is precisely 0? Or is my logic wrong?
I know I need some optimization to get this to provide a timely answer but I am just trying to get it to produce correct answers.
Let me generalize your questions to two questions:
1) What specifically is wrong with this program?
2) How do I figure out where a problem is in a program?
Others have already answered the first part, but to sum up:
Problem #1: Math.Pow uses double-precision floating point numbers, which are only accurate to about 15 decimal places. They are unsuitable for doing problems that require perfect accuracy involving large integers. If you try to compute, say, 1000000000000000000 - 1, in doubles, you'll get 1000000000000000000, which is an accurate answer to 15 decimal places; that's all we guarantee. If you need a perfectly accurate answer for working on large numbers, use longs for results less than about 10 billion billion, or the large integer mathematics class in System.Numerics that will ship with the next version of the framework.
Problem #2: There are far more efficient ways to compute modular exponents that do not involve generating huge numbers; use them.
However, what we've got here is a "give a man a fish" situation. What would be better is to teach you how to fish; learn how to debug a program using the debugger.
If I had to debug this program the first thing I would do is rewrite it so that every step along the way was stored in a local variable:
double intCount2 = 91;
double intHolder = 0;
for (int i = 0; i <= intCount2; i++)
{
double cube = Math.Pow(i, 3) - 1;
double remainder = cube % intCount2;
if (remainder == 0)
{
if (cube != 0)
{
Console.WriteLine(i);
intHolder += i;
}
}
}
Now step through it in the debugger with an example where you know the answer is wrong, and look for places where your assumptions are violated. If you do so, you'll quickly discover that 1000000 cubed minus 1 is not 99999999999999999, but rather 1000000000000000000.
So that's advice #1: write the code so that it is easy to step through in the debugger, and examine every step looking for the one that seems wrong.
Advice #2: Pay attention to quiet nagging doubts. When something looks dodgy or there's a bit you don't understand, investigate it until you do understand it.
Wikipedia has an article on Modular exponentiation that you may find informative. IIRC, Python has it built in. C# does not, so you'll need to implement it yourself.
Don't compute powers modulo n using Math.Pow; you are likely to experience overflow issues among other possible issues. Instead, you should compute them from first principles. Thus, to compute the cube of an integer i modulo n first reduce i modulo n to some integer j so that i is congruent to j modulo n and 0 <= j < n. Then iteratively multiply by j and reduce modulo n after each multiplication; to compute a cube you would perform this step twice. Of course, that's the native approach but you can make this more efficient by following the classic algorithm for exponentiation by using exponentiation by squaring.
Also, as far as efficiency, I note that you are unnecessarily computing Math.Pow(i, 3) - 1 twice. Thus, at a minimum, replace
if ((Math.Pow(i, 3) - 1) % intCount2 == 0) {
if ((Math.Pow(i, 3) - 1) != 0) {
Console.WriteLine(i);
intHolder += i;
}
}
with
int cubed = Math.Pow(i, 3) - 1;
if((cubed % intCount2 == 0) && (cubed != 0)) {
Console.WriteLine(i);
intHolder += i;
}
Well, there's something missing or a typo...
"intHolder1" should presumably be "intHolder" and for intCount2=91 to result in 8 the increment line should be:-
intHolder ++;
I don't have a solution to your problem, but here's just a piece of advice :
Don't use floating point numbers for calculations that only involve integers... Type int (Int32) is clearly not big enough for your needs, but long (Int64) should be enough : the biggest number you will have to manipulate will be (10 ^ 11 - 1) ^ 3, which is less than 10 ^ 14, which is definitely less than Int64.MaxValue. Benefits :
you do all your calculations with 64-bit integers, which should be pretty efficient on a 64-bit processor
all the results of your calculations are exact, since there are no approximations due the internal representation of doubles
Don't use Math.Pow to calculate the cube of an integer... x*x*x is just as simple, and more efficient since it doesn't need a conversion to/from double. Anyway, I'm not very good at math, but you probably don't need to calculate x^3... check the links about modular exponentiation in other answers