Trying to make a Prime Number Checker And Came across issues - c#

I'm new to coding on C# and thought I should try to make a Prime number checker, where you would input a number and it would be checked to see if it was prime or not. I wanted to try and use functions but came across some issues and I am a bit confused. Also, I believe my logic is also wrong but I'm not sure how to fix it. Here is my code any help is appreciated, also could you explain each part of your logic if you fix it:
internal class Program
{
static void Main(string[] args)
{
int number = Convert.ToInt32(Console.ReadLine());
IsNumberPrime();
Console.ReadKey();
}
static int IsNumberPrime(int number)
{
if (number <= 0)
{
Console.WriteLine(number + " is " + "not Prime");
}
else if (number == 1)
{
Console.WriteLine(number + " is " + "not Prime");
}
else if (number > 1)
{
for (int a = 2; number % a == 0; a++)
{
if (number % a == 0)
{
Console.WriteLine(number + " is " + "not Prime");
}
else
{
Console.WriteLine(number + " is " + " Prime");
}
}
}
}
}

There are several issues in your code, it's completely wrong.
first I will focus on the logical problems in your code.
you are not using the return value, so you can change the return type to void.
you should pass number as a parameter to the method IsNumberPrime.
you should modify the condition in the for a loop.
you should move the Console.WriteLine(number + " is Prime"); outside the for loop.
static void IsNumberPrime(int number)
{
if (number <= 0)
{
Console.WriteLine(number + " is not Prime");
}
else if (number == 1)
{
Console.WriteLine(number + " is not Prime");
}
else if (number > 1)
{
for (int a = 2; number > a; a++)
{
if (number % a == 0)
{
Console.WriteLine(number + " is not Prime");
return;
}
}
Console.WriteLine(number + " is Prime");
}
}
Now comes to the performance, you can run the loop till the square root of the number, not till the number, which will improve the performance of the code. also, no need to increment the value of a by 1, you can increment by 2 (first check divide by 2 and then just check divide by the odd numbers, no need to check with the other even numbers).
Here is the optimized code.
static void IsNumberPrime(int number)
{
if (number <= 1)
{
Console.WriteLine(number + " is " + "not Prime");
return;
}
if (number == 2)
{
Console.WriteLine(number + " is " + " Prime");
return;
}
if (number % 2 == 0)
{
Console.WriteLine(number + " is " + "not Prime");
return;
}
for (int i = 3; i <= Math.Sqrt(number); i = i + 2)
{
if (number % i == 0)
{
Console.WriteLine(number + " is " + "not Prime");
return;
}
}
Console.WriteLine(number + " is " + " Prime");
}

My comments will make your solution run, I didn't check the algorithm for Primes. Your Main function is calling IsNumberPrime() function which expects an integer value in its parameter.
Another remark is that the IsNumberPrime returns an integer value. Because you’re logging the results to the console, you should change the return type in the method declaration to void. Below are my adjustments to your code:
static void Main(string[] args)
{
int number = Convert.ToInt32(Console.ReadLine());
IsNumberPrime(number);
Console.ReadKey();
}
static void IsNumberPrime(int number)
{
if (number <= 0)
{
Console.WriteLine(number + " is " + "not Prime");
}
else if (number == 1)
{
Console.WriteLine(number + " is " + "not Prime");
}
else if (number > 1)
{
for (int a = 2; number % a == 0; a++)
{
if (number % a == 0)
{
Console.WriteLine(number + " is " + "not Prime");
}
else
{
Console.WriteLine(number + " is " + " Prime");
}
}
}
}

Related

I have an issue with converting numbers to words

so i'm having an issue with the decimal part where the number that you input in the console is for example 0,02 and it gives in words only 2 out of the 3 characters (skips the second 0) i tried many solutions including just doing an if() where i have a double mn = 0.9 but i found out that the if works only to 0 it accepts the variable that i made but its seems like it doesnt understands it. If you have any idea how i can fix this glad to hear
P.S I've attached the whole code on the other paragraph. Thank you!
what i want to happen Input 0,02 ---> output zero point zero two
what is happening Input - 0,02 ----> output zero point 2
static void Main(string[] args)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
// OT VIKTOR BOTKOV 304sr
try
{
Console.WriteLine("Въведете число.....:");
string number = Console.ReadLine();
number = ConvertAmount(double.Parse(number));
Console.WriteLine("Числото изписано в думи е : \n{0}", number);
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static String[] units = { "нула", "едно", "две", "три",
"четири", "пет", "шест", "седем", "осем", "девет", "десет", "единайсет",
"дванайсет", "тринайсет", "четиринайсет", "петнайсет", "шеснайсет",
"седемнайсет", "осемнайсет", "деветнайсет" };
private static String[] tens = { "", "", "двайсет", "трийсет", "четиресет",
"педесет", "шейсет", "седемдесет", "осемдесет", "деведесет" };
private static String[] hundreds = {"","сто", "двеста", "триста","четиристотин",
"петстотин", "шестстотин", "седемстотин", "осемстотин", "деветстотин" };
private static String[] thousands = {"","хиляда","две хиялди", "три хиляди","четири хиляди",
"пет хиляди", "шест хиляди", "седем хиляди", "осем хиляди", "девет хиляди" };
private static String[] unitsс = { "нула ", "един", "два", };
public static String ConvertAmount(double amount)
{
try
{
double mn = 0.09;
Int64 amount_int = (Int64)amount;
Int64 amount_dec = (Int64)Math.Round((Decimal)(amount - (double)(amount_int)) * 100);
if (amount_dec == 0)
{
return Convert(amount_int) + " лв.";
}
else if (amount_int <= mn)
{
return Convert(amount_int) + " Цяло и " + " Нула " + Convert(amount_dec) + " ст.";
}
else
{
return Convert(amount_int) + " лв. и " + Convert(amount_dec) + " ст.";
}
}
catch (Exception e)
{
}
return "";
}
public static String Convert(Int64 i)
{
Console.OutputEncoding = System.Text.Encoding.Unicode;
if (i<=2)
{
return unitsс[i];
}
if (i < 20)
{
return units[i];
}
if (i < 100)
{
return tens[i / 10] + ((i % 10 > 0) ? " и " + Convert(i % 10) : "");
}
if (i < 1000)
{
return hundreds[i / 100] + ((i % 100 > 0) ? " и " + Convert(i % 100) : "");
}
if (i < 100000)
{
return Convert(i / 1000) + " Хиляди "
+ ((i % 1000 > 0) ? " " + Convert(i % 1000) : "");
}
else if (i < 1000000)
{
return Convert(i / 10000) + " Хиляди "
+ ((i % 10000 > 0) ? " и " + Convert(i % 10000) : "");
}
if (i < 10000000)
{
return Convert(i / 1000000) + " Милиона "
+ ((i % 1000000 > 0) ? " " + Convert(i % 1000000) : "");
}
if (i < 100000000)
{
return Convert(i / 1000000) + " Милиона "
+ ((i % 1000000 > 0) ? " и " + Convert(i % 1000000) : "");
}
if (i < 1000000000)
{
return Convert(i / 1000000) + " Милиона "
+ ((i % 1000000 > 0) ? " " + Convert(i % 1000000) : "");
}
if (i < 10000000000)
{
return Convert(i / 1000000000) + " Милиaрда "
+ ((i % 1000000000 > 0) ? " " + Convert(i % 1000000000) : "");
}
return Convert(i / 1000000000000) + " "
+ ((i % 1000000000000 > 0) ? " " + Convert(i % 10000000000000) : "");
}
}

Implement a recursive program that displays all combinations of operators to reach a given sum

I have to write a program that displays all the combinations of operators( + and -), to put between numbers from 1 to N (N>=2), in order to reach a targeted value X. It should write "N/A" if there is no possibility.
For the input:
n=6
x=3
It displays:
1 + 2 + 3 - 4 - 5 + 6 = 3
1 + 2 - 3 + 4 + 5 - 6 = 3
1 - 2 - 3 - 4 + 5 + 6 = 3
using System;
namespace ConsoleApp1
{
class Program
{
static bool counter;
static void Generate(int n, int x, int currentIndex, int result, string expression)
{
counter = true;
if (currentIndex == n + 1)
{
if (result == x)
{
Console.WriteLine(expression + " = " + x);
}
return;
}
Generate(n, x, currentIndex + 1, result + currentIndex, expression + " + " + currentIndex);
Generate(n, x, currentIndex + 1, result - currentIndex, expression + " - " + currentIndex);
}
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int x = Convert.ToInt32(Console.ReadLine());
const int doi = 2;
Generate(n, x, doi, 1, "1");
if (!counter)
{
Console.WriteLine("N/A");
}
Console.ReadLine();
}
}
}
It gives me the error : JRM003 (Error) : Don't use static fields. (line: 7, character: 7).
Where can I place the "counter" in order to track if there is possibility of reaching to the targeted value, and get rid of the error.
Here's how I'd do it. Count in binary treating 0 as subtraction and 1 as addition:
public static void Main(string[] args)
{
int n, x;
String response1, response2;
Console.Write("Enter a value for 'n' [n>=2]: ");
response1 = Console.ReadLine();
Console.Write("Enter a value for 'x': ");
response2 = Console.ReadLine();
if (int.TryParse(response1, out n) && int.TryParse(response2, out x))
{
if (n >= 2)
{
List<String> solutions = new List<string>();
int[] numbers = Enumerable.Range(1, n).ToArray();
int width = numbers.Length - 1;
int max = (int)Math.Pow(2, numbers.Length - 1);
for(int i=0; i < max; i++)
{
int sum = numbers[0];
String binary = Convert.ToString(i, 2).PadLeft(width, '0');
String equation = numbers[0].ToString();
for(int d=0; d<binary.Length; d++)
{
char operation = binary[d];
equation = equation + ((operation == '0') ? " - " : " + ") + numbers[d + 1];
sum = sum + ((operation == '0') ? -1 : 1) * numbers[d + 1];
}
equation = equation + " = " + sum;
if (sum == x)
{
solutions.Add(equation);
}
}
if (solutions.Count == 0)
{
Console.WriteLine("N/A");
}
else
{
foreach(String solution in solutions)
{
Console.WriteLine(solution);
}
}
}
else
{
Console.WriteLine("'n' must be greater than or equal to 2.");
}
}
else
{
Console.WriteLine("Invalid value for 'n' or 'x'!");
}
Console.WriteLine("Press Enter to Quit.");
Console.ReadLine();
}
Output:
Enter a value for 'n' [n>=2]: 6
Enter a value for 'x': 3
1 - 2 - 3 - 4 + 5 + 6 = 3
1 + 2 - 3 + 4 + 5 - 6 = 3
1 + 2 + 3 - 4 - 5 + 6 = 3
Press Enter to Quit.

C# - Keeping total number of correct guesses inside a variable

Beginner to programming & have been assigned a heads or tails coin flip project.
I've figured out how to make it randomly generate the number of requested flips and print out the answers. However, I'm supposed to have it add up how many times the user's input came up into the correctCount variable and I can't find anywhere how to do it. I've tried searching on here and different sites from searching throughout Google. I assume I need to take their string input and convert it somehow, like if result == string, then correctCount + 1 basically, but can't figure out how to make that happen since you can't do that with int & string. Any info or hints would be very helpful - thank you!
class Coin
{
static void Main(string[] args)
// UserInput
{
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine() + "\n";
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
int correctCount = 0;
int heads = 0;
int tails = 1;
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
if (result == 0)
{
Console.WriteLine("Heads!");
}
else
{
Console.WriteLine("Tails!");
}
}
Console.WriteLine("Your guess, " + headsOrTailsGuess + "came up " + correctCount + " time(s).");```
As PMF mentioned, you have to not only receive user choice, but also analyse it.
A simple comparison should be more that enough here, although you might want to add some validation to user input.
static void Main(string[] args)
// UserInput
{
int choice; //variable for parsed user choice
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine() + "\n";
if(headsOrTailsGuess.ToLower().Trim() == "heads"){ //here you look if its heads
choice = 0;
}
else{ //we can write additional if here to avoid other options from counting as tails
choice = 1;
}
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
int correctCount = 0;
int heads = 0;
int tails = 1;
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
if (result == 0)
{
Console.WriteLine("Heads!");
}
else
{
Console.WriteLine("Tails!");
}
if(result == choice){ //comparing result to parsed choice and incrementing the counter
correctCount++;
}
}
Console.WriteLine("Your guess, " + headsOrTailsGuess + "came up " + correctCount + " time(s).");
}
Here's another way to do it using Linq.
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
// UserInput
{
Console.Write("Guess which will have more: heads or tails?");
string headsOrTailsGuess = Console.ReadLine();
Console.Write("\n" + "How many times shall we flip the coin? ");
int numberOfFlips = int.Parse(Console.ReadLine() + "\n");
// Declare variables
List<string> resultList = new List<string>();
Random rand = new Random();
for (int i = 0; i < numberOfFlips; i++)
{
int result = rand.Next(0, 2);
resultList.Add(result == 1? "Heads!" : "Tails!");
}
var guessCount = resultList.Where(a=>a.ToUpper().Contains(headsOrTailsGuess.ToUpper())).Count();
resultList.ForEach( a=> Console.WriteLine(a));
Console.WriteLine("Your guess, " + headsOrTailsGuess + " came up " + guessCount + " time(s).");
Console.WriteLine(headsOrTailsGuess);
}
}
}
using System;
Console.WriteLine("Guess which will have more: heads or tails?");
var headsChosen = false;
var input = string.Empty;
do
{
input = Console.ReadLine();
headsChosen = input.ToLower() == "heads";
} while (input.ToLower() != "heads" && input.ToLower() != "tails");
Console.WriteLine("How many times shall we flip the coin?");
var flips = 0;
do
{
} while (!int.TryParse(Console.ReadLine(), out flips));
var rnd = new Random();
var heads = 0;
var tails = 0;
for (int i = 0; i < flips; i++)
{
if (rnd.Next(0, 2) == 0)
{
Console.WriteLine("Heads!");
heads++;
}
else
{
Console.WriteLine("Tails!");
tails++;
}
}
var userGuessed = (headsChosen && heads > tails) || (!headsChosen && tails > heads);
Console.WriteLine($"You {(userGuessed ? "guess" : "loose")}!");

I really dont understand why after I give input to the code it does nothing

It seems to be perfectly made and I don't think there is an error behind it. Can someone help me to do analyze this more? Am I missing something ? It is about area conversion anyway.
double numberOne = 0;
Boolean programRunning = true;
while (programRunning == true)
{
OutputMenu();
int choice = OutputMenu();
if (choice == 9)
{
programRunning = false;
break;
}
Console.Clear();
InputNumber(ref numberOne);
if (choice == 1)
{
double Result = numberOne / 10000;
Console.WriteLine(numberOne + " / " + 10000 + " = " + Result);
}
else if (choice == 2)
{
double Result = numberOne / 10000;
Console.WriteLine(numberOne + " / " + 10000+ " = " + Result);
}
else if (choice == 3)
{
double Result = numberOne / 100;
Console.WriteLine(numberOne + " / " + 100+ " = " + Result);
}
else if (choice == 4)
{
double Result = numberOne * 1.55e+9;
Console.WriteLine(numberOne + " * " + 1.55e+9 + " = " + Result);
}
else if (choice == 5)
{
double Result = numberOne / 144;
Console.WriteLine(numberOne + " / " + 144 + " = " + Result);
}
}
}
private static int OutputMenu()
{
Console.WriteLine("1. cm2 to m2");
Console.WriteLine("2. m2 to ha");
Console.WriteLine("3. ha to km²");
Console.WriteLine("4. km2 to sq in");
Console.WriteLine("5. in² to ft²");
Console.WriteLine("9. Exit");
int choice;
bool pass = false;
while (!pass)
{
Console.WriteLine("Please enter the corresponding number to your option. ");
pass = int.TryParse(Console.ReadLine(), out choice);
if (pass && (choice == 1 || choice == 2 || choice == 3 || choice == 4 || choice == 5 || choice == 9))
{
}
else
{
Console.WriteLine("Please enter a valid number");
pass = false;
}
}
return Convert.ToInt32(Console.ReadLine());
}
private static void InputNumber(ref double number1)
{
bool pass = false; while (!pass)
{
Console.WriteLine("Please enter the first number");
pass = double.TryParse(Console.ReadLine(), out number1);
if (pass)
{
}
else
{
Console.WriteLine("Please enter a valid number");
static void Main()
{
double numberOne = 0;
while (true)
{
int choice = OutputMenu();
if (choice == 9)
{
break;
}
Console.Clear();
InputNumber(ref numberOne);
if (choice == 1)
{
double Result = numberOne / 10000;
Console.WriteLine(numberOne + " / " + 10000 + " = " + Result);
}
else if (choice == 2)
{
double Result = numberOne / 10000;
Console.WriteLine(numberOne + " / " + 10000+ " = " + Result);
}
else if (choice == 3)
{
double Result = numberOne / 100;
Console.WriteLine(numberOne + " / " + 100+ " = " + Result);
}
else if (choice == 4)
{
double Result = numberOne * 1.55e+9;
Console.WriteLine(numberOne + " * " + 1.55e+9 + " = " + Result);
}
else if (choice == 5)
{
double Result = numberOne / 144;
Console.WriteLine(numberOne + " / " + 144 + " = " + Result);
}
}
}
private static int OutputMenu()
{
Console.WriteLine("1. cm2 to m2");
Console.WriteLine("2. m2 to ha");
Console.WriteLine("3. ha to km²");
Console.WriteLine("4. km2 to sq in");
Console.WriteLine("5. in² to ft²");
Console.WriteLine("9. Exit");
int choice;
while (true)
{
Console.WriteLine("Please enter the corresponding number to your option. Value has to fall between 1 and 5 or 9 ");
if(int.TryParse(Console.ReadLine(), out choice) && ((choice > 0 && choice < 6) || choice == 9)))
{
break;
}
else
{
Console.WriteLine("Please enter a valid number");
}
}
return choice;
}
private static void InputNumber(ref double number1)
{
while (true)
{
Console.WriteLine("Please enter the number to be converted");
if (double.TryParse(Console.ReadLine(), out number))
{
number1 = number;
break;
}
else
{
Console.WriteLine("Please enter a valid number");
}
}
This should work.

Best Fit Memory Allocation

I am trying to implement Best fit memory allocation. I have done the code, which i think should work but somehow it appears its getting stuck in the loop. I can't figure out why. The following is my code. I want to allocate jobs to the memory with the least memory waste.
public void bestFit(int job_size)
{
string str1 = "";
string str2 = "";
string str3 = "";
int memory_block = 99999;
int subscript = 0;
int initial_memory_waste = memory_block - job_array[0];
int job_counter = 0;
int counter = 1;
int memory_waste = 0;
while (counter <= memory_array.Length)
{
if (job_size > memory_array[counter - 1])
{
counter += 1;
}
else
memory_waste = memory_array[counter - 1] - job_size;
{
if (initial_memory_waste > memory_waste)
{
subscript = counter;
initial_memory_waste = memory_waste;
counter += 1;
}
}
}
queued_jobs = counter;
str3 = ("Job number: " + (queued_jobs).ToString() + " of size: " + job_size.ToString());
if (job_counter < job_array.Length)
{
bf_waiting_queue.Add(str3);
}
else
{
str1 = ("Job number: " + (job_counter).ToString() + " of size: " + job_size.ToString() + " is allocated to Memory block: " + (subscript).ToString() + " of size: " + memory_array[subscript - 1]).ToString();
memory_waste = memory_array[subscript - 1] - job_size;
str2 = ("Memory waste is: " + memory_waste.ToString());
bf_total_memory_waste += memory_waste;
memory_array[counter - 1] = (memory_array[counter - 1] - job_size);
bf_jobsInMemory.Add(str1 + "\t" + str2);
job_counter += 1;
counter = 1;
}
}
Aside from the braces issue others pointed out, your logic makes it possible for you to never increment 'counter', which is why you are stuck in the loop. The following reorganization is cleaner and guarantees you always increment 'counter'. Also, a couple of comments couldn't hurt.
while (counter <= memory_array.Length)
{
// If block fits, consider it
if (job_size <= memory_array[counter - 1])
{
memory_waste = memory_array[counter - 1] - job_size;
// If this block is less wasteful, remember it
if (initial_memory_waste > memory_waste)
{
subscript = counter;
initial_memory_waste = memory_waste;
}
}
// Next block
counter += 1;
}

Categories