Need help, cant figure out how to validate this as binary. Any help appreciated I know I am a noob.
Tried this... didn't work so well
// } while (binaryStringIsValid(binaryStr) == false);
//static bool binaryStringIsValid(string binaryStr)
//{
// bool valid = false;
// foreach (char ch in binaryStr)
// {
// if (ch != '0' && ch != '1')
// {
// Console.WriteLine("String Is Invalid");
// }
// }valid = binaryStr.Length < 9;
// return valid;
//}
{
int digits = 0;
string binaryStr = "";
int sum = 0;
int remainder;
int po2 = 0;
Console.WriteLine("Enter a valid binary string: ");
digits = Convert.ToInt32(Console.ReadLine());
while (digits > 0)
{
remainder = digits % 10;
sum = sum + remainder * Convert.ToInt32(Math.Pow(2, po2));
po2 = po2 + 1;
digits = digits / 10;
}
Console.WriteLine("Your binary string is equal to the decimal
number: " + sum);
Console.ReadKey();
}
I need to make sure it has only 0's and 1's and is <9 characters long.
Check this code
public bool IsBinary(string input) => new Regex("^[01]{1,9}$").IsMatch(input);
Related
Write a console application that calculates the sum of a given number of integers.
The numbers are entered one per line, and the application will read one by one until the user writes the character instead of a number. When the user has typed x, the application knows that all the numbers in the string have been entered and displays their amount.
If the first thing the user enters is the x character, the application will return 0.
Example:
For input:
2
5
-3
1
X
The console will display:
5
and this is my code
string[] answer = new string[10];
int sum = 0
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Can anyone tell me why is not working?
First of all, the working code (I didn't focus on X but on any char that isn't a number):
int n;
int sum = 0;
while (int.TryParse(Console.ReadLine(), out n))
{
sum += n;
}
Console.Write(sum );
Console.ReadKey();
Secondly, your code doesn't work because your array is full of 'null'-s when you try to parse the content of its first cell in 'answer[i]'
Here's a dumb (a bit) fix for your code:
string[] answer = new string[10];
//HERE
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
sum += Int32.Parse(answer[i]);
if (answer[i] == "x")
{
Console.WriteLine(sum);
}
answer[i] = Console.ReadLine();
}
Console.Read();
Another problem with your code is you don't stop the iteration once "x" is entered, but continue until the end of the array (until it's been 10 times).
Here's kind of a complete fix for your code:
string[] answer = new string[10];
for (int i = 0; i < answer.Length; i++)
{
answer[i] = "0";
}
int sum = 0;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
break;
}
sum += Int32.Parse(answer[i]);
}
Console.WriteLine(sum);
Console.Read();
Few issues:
I think order of your code instructions is not correct. First time when you parse your array element, its not yet initialized.
int sum = 0 is missing ; at the end.
You should always use TryParse instead of Parse
Try the following code:
string[] answer = new string[10];
int sum = 0, number;
for (int i = 0; i < answer.Length; i++)
{
answer[i] = Console.ReadLine();
if (answer[i] == "x")
{
Console.WriteLine(sum);
break;
}
if(Int32.TryParse(answer[i], out number))
sum += number;
}
I gave you your terminating 'x'
var answer = Console.ReadLine();
var sum = 0;
while (answer != "x")
{
if (Int32.TryParse(answer, out var value))
{
sum += value;
}
answer = Console.ReadLine();
}
Console.WriteLine(sum);
You should check for "x" first since int.Parse("x") throws exception:
Wrong order (current code):
sum += Int32.Parse(answer[i]); // <- this will throw exception on "x" input
if (answer[i] == "x") {
...
}
...
Right order:
if (answer[i] == "x") {
...
}
else
sum += Int32.Parse(answer[i]);
...
in order to check for syntax errors (e.g. when user inputs "bla-bla-bla") I suggest int.TryParse instead of int.Parse and let's get rid of the array why should we collect the items (esp. with unwanted restriction of 10 items)?
// long: we don't want overflow, e.g. 2000000000, 1000000000
long sum = 0;
while (true) {
// Trim() - let's be nice and allow user put leading/trailing spaces
string input = Console.ReadLine().Trim();
if (string.Equals("x", input, StringComparison.OrdinalIgnoreCase))
break;
if (int.TryParse(input, out var item))
sum += item;
else {
//TODO: Incorrect input, neither integer nor "x" (e.g. "abracadabra")
}
}
Console.WriteLine(sum);
Console.Read();
I wrote below code for generating my 8 digit character number, increment should happen from left to right.
suppose my starting Number is ABC00001 the next increment number will be ABC00002
number will increment up to 9 and after 9 it will change to A .
eg: ABC00009 -- >ABC00000A --> ABC00000B --> .... -->ABC00000Z
after Z it will change last second digit number as ABC0000A1 --> ABC0000A2 ...
public static string GeneratedNextevcPrimakryKey()
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
string str = string.Empty;
var maxNumber = "ONC0BJKZ";
string splitnumber = maxNumber.Substring(3, 5);
char[] temp = splitnumber.ToCharArray();
//find last index number/character
for (int i = splitnumber.Length - 1; i >= 0; i--)
{
if (char.IsNumber(splitnumber[i]))
{
int fifthvalue = Convert.ToInt32(splitnumber[i].ToString());
//increment 5th digit character
if (fifthvalue == 9)
{
temp[i] = 'A';
break;
}
else
{
fifthvalue = fifthvalue + 1;
string f = Convert.ToString(fifthvalue);
temp[i] = Convert.ToChar(f);
//sb.Append(fifthvalue);
break;
}
}
else
{
char letter = splitnumber[i];
char nextChar = new char();
if (letter == 'z')
{
string strvalue = Convert.ToString(1);
temp[i] = Convert.ToChar(strvalue);
}
else if (letter == 'Z')
{
//last digit character
string strvalue = Convert.ToString(1);
temp[i] = Convert.ToChar(strvalue);
str = new string(temp);
break;
}
else
nextChar = (char)(((int)letter) + 1);
temp[i] = nextChar;
str = new string(temp);
break;
}
}
return str;
}
You can try to implement Base36
void Main()
{
// 17 would be the number you want to convert to your ABC format
var result = ToBase36(17);
Console.WriteLine(result);
// Will print "ABC00000H"
}
private static string ToBase36(ulong value)
{
const string base36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sb = new StringBuilder(9);
do
{
sb.Insert(0, base36[(byte)(value % 36)]);
value /= 36;
} while (value != 0);
var paddedString = "ABC" + sb.ToString().PadLeft(6, '0');
return paddedString;
}
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 6 years ago.
Improve this question
I would like to write a code that shows a list of prime number one number to another number. For example from 1 to 8, it would be 2, 3, 5, 7. I got a code from "Check if number is prime number" by user1954418 because I did not know where to begin, so I take NO credit whatsoever for the code.
int num1;
Console.WriteLine("Prime Number:");
num1 = Convert.ToInt32(Console.ReadLine());
if (num1 == 0 || num1 == 1)
{
Console.WriteLine(num1 + " is not prime number");
Console.ReadLine();
}
else
{
for (int a = 2; a <= num1 / 10; a++)
{
if (num1 % a == 0)
{
Console.WriteLine(num1 + " is not prime number");
return;
}
}
Console.WriteLine(num1 + " is a prime number");
Console.ReadLine();
}
Here is a sample that should work. The code from isPrime I just got from here Here
Then In the main function just have the loop that goes from you starting number to the end number, and runs the isPrime function on each one.
Here is the code:
class Program
{
static void Main(string[] args)
{
int numberStart;
int numberEnd;
// Take in the start point and the end point
Console.WriteLine("Starting Number:");
if(!int.TryParse(Console.ReadLine(), out numberStart)){
Console.WriteLine("Your input is invalid.");
}
Console.WriteLine("Ending Number:");
if (!int.TryParse(Console.ReadLine(), out numberEnd))
{
Console.WriteLine("Your input is invalid.");
}
// Loop from the first number to the last number, and check if each one is prime
for (int number = numberStart; number < numberEnd; number++)
{
Console.WriteLine(number + " is prime?");
Console.WriteLine(isPrime(number) + "\n");
}
Console.ReadLine();
}
// Function for checking if a given number is prime.
public static bool isPrime(int number)
{
int boundary = (int) Math.Floor(Math.Sqrt(number));
if (number == 1) return false;
if (number == 2) return true;
for (int i = 2; i <= boundary; ++i)
{
if (number % i == 0) return false;
}
return true;
}
}
Note that the function isPrime() only checks up to the root, as it is unnecessary to check further as mentioned by the user from the link.
Hope it helps :)
Make it simple; following code will help you:
Console.WriteLine("Enter the Limit:");
int Limit;
if (!int.TryParse(Console.ReadLine(), out Limit))
{
Console.WriteLine("Invalid input");
}
Console.WriteLine("List of prime numbers between 0 and {0} are :",Limit);
for (int i = 2; i < Limit; i++)
{
if (checkForPrime(i))
Console.WriteLine(i);
}
Console.ReadKey();
Where checkForPrime() is defined as follows:
public static bool checkForPrime(int Number)
{
for (int a = 2; a <= Number / 2; a++)
{
if (Number % a == 0)
{
return false;
}
}
return true;
}
Here's some code I wrote/copied to do this in one of my projects. It could probably be a little smoother but it gets the job done.
// Found this awesome code at http://csharphelper.com/blog/2014/08/use-the-sieve-of-eratosthenes-to-find-prime-numbers-in-c/
// This creates a List of Booleans where you can check if a value x is prime by simply doing if(is_prime[x]);
public static bool[] MakeSieve(int max)
{
var sqrt = Math.Sqrt((double)max);
// Make an array indicating whether numbers are prime.
var isPrime = new bool[max + 1];
for (var i = 2; i <= max; i++) isPrime[i] = true;
// Cross out multiples.
for (var i = 2; i <= sqrt; i++)
{
// See if i is prime.
if (!isPrime[i]) continue;
// Knock out multiples of i.
for (var j = i * 2; j <= max; j += i)
isPrime[j] = false;
}
return isPrime;
}
public static List<int> GetListOfPrimes(int max)
{
var isPrime = MakeSieve(max);
return new List<int>(Enumerable.Range(1, max).Where(x => isPrime[x]));
//var returnList = new List<int>();
//for (int i = 0; i <= max; i++) if (isPrime[i]) returnList.Add(i);
//return returnList;
}
Here's an example of usage:
static void Main(string[] args)
{
var x = GetListOfPrimes(8);
foreach (var y in x)
{
Console.WriteLine(y);
}
Console.Read();
}
Is there any way to convert very large binary, decimal and hexadecimal numbers to each other?
I have to use it to simulate addressing process up to 256 bits.
I want to do the following conversions (and if it's possible, store them in one object)
very large binary number -> very large decimal number
very large binary number -> very large hexadecimal number
very large decimal number -> very large binary number
very large decimal number -> very large hexadecimal number
very large hexadecimal number -> very large binary number
very large hexadecimal number -> very large decimal number
very large binary number -> string
very large decimal number -> string
very large hexadecimal number -> string
The possibility of splitting and joining very large binary numbers is very important.
If it's possible, I would use a class supported solution, and avoid manual conversion from one number base to another using byte[] type.
I've tried the BigInteger class, it can store very large numbers, but can't convert them to another number base.
Solution by Andrew Jonkers :
//Convert number in string representation from base:from to base:to.
//Return result as a string
public static String Convert(int from, int to, String s)
{
//Return error if input is empty
if (String.IsNullOrEmpty(s))
{
return ("Error: Nothing in Input String");
}
//only allow uppercase input characters in string
s = s.ToUpper();
//only do base 2 to base 36 (digit represented by characters 0-Z)"
if (from < 2 || from > 36 || to < 2 || to > 36)
{ return ("Base requested outside range"); }
//convert string to an array of integer digits representing number in base:from
int il = s.Length;
int[] fs = new int[il];
int k = 0;
for (int i = s.Length - 1; i >= 0; i--)
{
if (s[i] >= '0' && s[i] <= '9') { fs[k++] = (int)(s[i] - '0'); }
else
{
if (s[i] >= 'A' && s[i] <= 'Z') { fs[k++] = 10 + (int)(s[i] - 'A'); }
else
{ return ("Error: Input string must only contain any of 0-9 or A-Z"); } //only allow 0-9 A-Z characters
}
}
//check the input for digits that exceed the allowable for base:from
foreach(int i in fs)
{
if (i >= from) { return ("Error: Not a valid number for this input base"); }
}
//find how many digits the output needs
int ol = il * (from / to+1);
int[] ts = new int[ol+10]; //assign accumulation array
int[] cums = new int[ol+10]; //assign the result array
ts[0] = 1; //initialize array with number 1
//evaluate the output
for (int i = 0; i < il; i++) //for each input digit
{
for (int j = 0; j < ol; j++) //add the input digit
// times (base:to from^i) to the output cumulator
{
cums[j] += ts[j] * fs[i];
int temp = cums[j];
int rem = 0;
int ip = j;
do // fix up any remainders in base:to
{
rem = temp / to;
cums[ip] = temp-rem*to; ip++;
cums[ip] += rem;
temp = cums[ip];
}
while (temp >=to);
}
//calculate the next power from^i) in base:to format
for (int j = 0; j < ol; j++)
{
ts[j] = ts[j] * from;
}
for(int j=0;j<ol;j++) //check for any remainders
{
int temp = ts[j];
int rem = 0;
int ip = j;
do //fix up any remainders
{
rem = temp / to;
ts[ip] = temp - rem * to; ip++;
ts[ip] += rem;
temp = ts[ip];
}
while (temp >= to);
}
}
//convert the output to string format (digits 0,to-1 converted to 0-Z characters)
String sout = String.Empty; //initialize output string
bool first = false; //leading zero flag
for (int i = ol ; i >= 0; i--)
{
if (cums[i] != 0) { first = true; }
if (!first) { continue; }
if (cums[i] < 10) { sout += (char)(cums[i] + '0'); }
else { sout += (char)(cums[i] + 'A'-10); }
}
if (String.IsNullOrEmpty(sout)) { return "0"; } //input was zero, return 0
//return the converted string
return sout;
}
I had the same issue once. I wrote simple method which changes array of decimal numbers to array of binary numbers.
private int[] ConvertDecimalCharArrayToBinaryCharArray(int[] decimalValues)
{
List<int> result = new List<int>();
bool end = false;
while (end == false)
{
result.Add(decimalValues[decimalValues.Length - 1] % 2);
int previous = 0;
bool allzeros = true;
for (int i = 0; i < decimalValues.Length; i++)
{
var x = decimalValues[i];
if (x != 0)
{
allzeros = false;
}
if (allzeros && i == decimalValues.Length - 1)
{
end = true;
}
var a = (x + previous) / 2;
if ((x + previous) % 2== 1)
{
previous = 10;
}
else
{
previous = 0;
}
decimalValues[i] = a;
}
}
result.RemoveAt(result.Count - 1);
result.Reverse();
return result.ToArray();
}
I have this task: Write an expression that checks if given positive integer number n (n ≤ 100) is prime. E.g. 37 is prime.
int number = int.Parse(Console.ReadLine());
for (int i = 1; i < 100; i++)
{
bool isPrime = (number % number == 0 && number % i == 0);
if (isPrime)
{
Console.WriteLine("Number {0} is not prime", number);
}
else
{
Console.WriteLine("Number {0} is prime", number);
break;
}
}
This doesn't seem to work. Any suggestioins?
int number = int.Parse(Console.ReadLine());
bool prime = true;
// we only have to count up to and including the square root of a number
int upper = (int)Math.Sqrt(number);
for (int i = 2; i <= upper; i++) {
if ((number % i) == 0) {
prime = false;
break;
}
}
Console.WriteLine("Number {0} is "+ (prime ? "prime" : "not prime"), number);
a. What are you expecting number % number to do?
b. Your isPrime check is "reset" each time through the loop. Something more like this is required:
bool isprime = true;
for(int i = 2; i < number; i++) {
// if number is divisible by i then
// isprime = false;
// break
}
// display result.
The problems are:
the for should start from 2 as any number will be dived by 1.
number % number == 0 - this is all the time true
the number is prime if he meats all the for steps so
else
{
Console.WriteLine("Number {0} is prime", number);
break;
}
shold not be there.
The code should be something like this:
int number = int.Parse(Console.ReadLine());
if (number == 1)
{ Console.WriteLine("Number 1 is prime");return;}
for (int i = 2; i < number / 2 + 1; i++)
{
bool isPrime = (number % i == 0);
if (isPrime)
{
Console.WriteLine("Number {0} is not prime", number);
return;
}
}
Console.WriteLine("Number {0} is prime", number);
please notice that I didn't test this...just wrote it here. But you should get the point.
Semi-serious possible solution with LINQ (need smaller range at least):
var isPrime = !Enumerable.Range(2, number/2).Where(i => number % i == 0).Any();
The Program checks the given number is prime number or not.
A prime number is a number that can only be divided by 1 and itself
class Program
{
bool CheckIsPrimeNumber(int primeNum)
{
bool isPrime = false;
for (int i = 2; i <= primeNum / 2; i++)
{
if (primeNum % i == 0)
{
return isPrime;
}
}
return !isPrime;
}
public static void Main(string[] args)
{
Program obj = new Program();
Console.Write("Enter the number to check prime : ");
int mPrimeNum = int.Parse(Console.ReadLine());
if (obj.CheckIsPrimeNumber(mPrimeNum) == true)
{
Console.WriteLine("\nThe " + mPrimeNum + " is a Prime Number");
}
else
{
Console.WriteLine("\nThe " + mPrimeNum + " is Not a Prime Number");
}
Console.ReadKey();
}
}
Thanks!!!
Here is for you:
void prime_num(long num)
{
bool isPrime = true;
for (int i = 0; i <= num; i++)
{
for (int j = 2; j <= num; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
Console.WriteLine ( "Prime:" + i );
}
isPrime = true;
}
}