My code:
int n = int.Parse(Console.ReadLine());
bool result= true;
if (n < 0)
{
n = -n;
}
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
result = false;
break;
}
}
if (result)
{
Console.WriteLine("Prime");
}
else
{
Console.WriteLine("Not prime");
}
So I want to make it when is negative number for example -11 to add 1 more - and make it positive I tried with:
if (n < 0)
{
n = -n;
}
But it didn't worked as I expect also I need when is 0 or 1 to say Not Prime
You have 3 conditions to check:
if n is 0 or 1, not a prime number
if n is 2, prime number
if n is greater than 2, you need to check if they have any divisors (if yes, they are not prime)
int n = int.Parse(Console.ReadLine());
bool result= true;
if (n < 0)
{
n = -n;
}
if (n<2)
result = false;
else if (n==2)
result = true;
else
for (int i = 2; i < n; i++)
{
if (n % i == 0)
{
result = false;
break;
}
}
if (result)
{
Console.WriteLine("Prime");
}
else
{
Console.WriteLine("Not prime");
}
Related
Trying to solve a simple c# question and I did but my teacher wants me to do it with a nestled loop instead of with a boolean.
Problem: Show all numbers from input number that is divisible by 3 and 7. If no number is found show "No number found".
How i solved it with bool:
Console.WriteLine("Put in a number: ");
int nummer = int.Parse(Console.ReadLine());
bool FoundLegitNumber = false;
for (int i = 1; i <= nummer; i++)
{
if (i % 3 == 0 && i % 7 == 0)
{
FoundLegitNumber = true;
Console.WriteLine($"The number {i} is evenly divisible by 3 and 7");
}
}
if (!FoundLegitNumber)
{
Console.WriteLine("Didnt find any number...");
}
How I'm trying to solve it with a for loop:
Console.WriteLine("Put in a number: ");
int nummer = int.Parse(Console.ReadLine());
for (int i = 0; i <= nummer; i++)
{
for (int j = 0; i >= j; j++)
{
if (i % 3 == 0 && i % 7 == 0)
{
Console.WriteLine($"The number {i} is evenly divisible by 3 and 7");
}
else if (j == 0)
{
Console.WriteLine("Didnt find any number...");
break;
}
}
}
I know, it doesnt make any sense but I cant figure out how to solve it. I know that I want to give J + 1 if (i % 3 == 0 && i % 7 == 0) was not true.
If you want a method that involves a nested for without distorting the basic problem, maybe you could add a dividers array like this:
int number = 21;
int[] dividers = new int[] { 3, 7 };
for (int i = 0; i <= number; i++)
{
bool matchAllDividers = true;
for (int j = 0; j < dividers.Length; j++)
{
if (i % dividers[j] != 0)
{
matchAllDividers = false;
break;
}
}
if (matchAllDividers)
{
Console.WriteLine("The number {0} is evenly divisible by all dividers".FormatWith(i));
}
else
{
Console.WriteLine("The number {0} is not evenly divisible by all dividers".FormatWith(i));
}
}
I'm trying to display last prime number for a given interval. For example:
if n is 10 last prime nubmer is 7
if n is 11 last prime nubmer is 11
if n is 14 last prime number is 13
etc...
public static uint LastPrimeNumberInInterval(uint n)
{
uint result = 0;
uint i = 2;
while (i <= n)
{
bool b = false;
while (i <= n / 2)
{
if (n % i == 0)
{
b = true;
break;
}
i++;
}
if (!b)
{
result = i;
}
i++;
}
return result;
}
but I'm stuck on displaying only correct answer when n is prime number. Can someone point out where is my fault?
You need to use a different variable in your nested loop and reset it for each number being checked.
public static uint LastPrimeNumberInInterval(uint n)
{
uint result = 0;
uint i = 2;
while (i <= n)
{
bool b = false;
uint j = 2;
while (j <= n / 2)
{
if (n % j == 0)
{
b = true;
break;
}
j++;
}
if (!b)
{
result = i;
}
i++;
}
return result;
}
I'm supposed to make a code in c# (microsoft visual studio 2017) that lets the user input six numbers, and then compare them to an array of six randomly generated numbers(with no duplicates).
If the user has one match, he's supposed to get a message saying he had one match, and different messages for two or three matches, and so on.
This is what I got so far:
static bool isValueInArray(int value, int[] a)
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] == value)
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
int min = 0;
int max = 6;
Random randnum = new Random();//random number generator
int[] numbers = new int[6];// generates six numbers
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = randnum.Next(min, max);//sets the numbers between 0 to 6
if(isValueInArray( i, numbers))
{
numbers[i] = randnum.Next(min, max);
}
}
try
{
Console.WriteLine("Hello and Welcome to our little game of lottery! lets see just how much luck you got!"); // greetings and instructions
Console.WriteLine("You'll now get to choose 6 different numbers between 0 to 6 to play with.");
Console.WriteLine("Go ahead and type them in.");
int[] lottery = new int[6];
for (int i = 0; i < lottery.Length; i++)
{
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
if (lottery[i] > 6)//checking if the numbers fit between 0 and 6
{
Console.WriteLine("whoops! the number you enetered isn't in range! please try again ^^");
break;
}
int x = 6;
for (int a = 0; a < lottery.Length; a++)
{
for (int b = 0; b < numbers.Length; b++)
{
if (lottery[a] == numbers[b])
{
a++;
x--;
if (x == 6)
{
Console.WriteLine("six match");
break;
}
else if (x == 5)
{
Console.WriteLine("five match");
break;
}
else if (x == 4)
{
Console.WriteLine("four match");
break;
}
else if (x == 3)
{
Console.WriteLine("three match");
break;
}
else if (x == 2)
{
Console.WriteLine("two match");
break;
}
else if (x == 1)
{
Console.WriteLine("one match");
break;
}
}
}
}
}
}
catch (FormatException)// checking if the input is in char format
{
Console.WriteLine("only numbers please!");
}
}
My problem is with the output. The program seems to go over all of the "else if" options and print all of them, instead of picking and printing just one of them.
You have everything mixed together. Write out the steps:
Generate numbers
Get input from user
Count number of matches
Print results
Each step should be performed separately.
// These should be the min/max lottery numbers
int min = 1;
int max = 100;
int numberOfLotteryNumbers = 6;
// Renamed for clarity
int[] lotteryNumbers = new int[numberOfLotteryNumbers];
int[] userNumbers = new int[numberOfLotteryNumbers];
// Step 1 - generate numbers
for (int i = 0; i < lotteryNumbers.Length; i++) {
int randomNumber;
do {
randomNumber = randnum.Next(min, max);
} while (isValueInArray(randomNumber, lotteryNumbers));
lotteryNumbers[i] = randomNumber;
}
// Step 2 - get numbers from user
for (int i = 0; i < lottery.Length; i++) {
int userInput;
do {
userInput = int.Parse(Console.ReadLine());
} while (userInput < min || userInput > max || isValueInArray(userInput, userNumbers));
userNumbers[i] = userInput;
}
// Step 3 - calc matches
int matches = 0;
for (int i = 0; i < userNumbers.Length; i++) {
if (isValueInArray(userNumbers[i], lotteryNumbers) {
matches += 1;
}
}
// Step 4 - print results
Console.WriteLine("There are {0} matches.", matches);
You may have to rearrange the code blocks in a way to get user input first, calculate the number of matches first, then display results as following code:
Note: Your approach to guarantee unique numbers in the randomly generated number ain't going to work as you expect to, you are passing "i" where you may want to pass "numbers[i]" instead to the isValueInArray" function. Let aside the idea that you will always end with values 0-5 in the array since you want 6 numbers.
int min = 0;
int max = 6;
Random randnum = new Random();//random number generator
int[] numbers = new int[6];// generates six numbers
for (int i = 0; i < numbers.Length; i++)
{
numbers[i] = randnum.Next(min, max);//sets the numbers between 0 to 6
if (isValueInArray(i, numbers))
{
numbers[i] = randnum.Next(min, max);
}
}
try
{
Console.WriteLine("Hello and Welcome to our little game of lottery! lets see just how much luck you got!"); // greetings and instructions
Console.WriteLine("You'll now get to choose 6 different numbers between 0 to 6 to play with.");
Console.WriteLine("Go ahead and type them in.");
int[] lottery = new int[6];
int x = 0;
//read user numbers
for (int i = 0; i < lottery.Length; i++)
{
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
while (lottery[i] > 6)//checking if the numbers fit between 0 and 6
{
Console.WriteLine("whoops! the number you enetered isn't in range! please try again ^^");
lottery[i] = int.Parse(Console.ReadLine()); // array to catch six numbers input
}
}
//count number of matches
for (int a = 0; a < lottery.Length; a++)
{
for (int b = 0; b < numbers.Length; b++)
{
if (lottery[a] == numbers[b])
{
//a++;
x++;
break;
}
}
}
//display results
if (x == 6)
{
Console.WriteLine("six matches");
}
else if (x == 5)
{
Console.WriteLine("five matches");
}
else if (x == 4)
{
Console.WriteLine("four matches");
}
else if (x == 3)
{
Console.WriteLine("three matches");
}
else if (x == 2)
{
Console.WriteLine("two matches");
}
else if (x == 1)
{
Console.WriteLine("one match");
}
}
catch (FormatException)// checking if the input is in char format
{
Console.WriteLine("only numbers please!");
}
Console.Read();
}
You can use a counter to achieve your goal. Just increment counter value on match:
int counter = 0;
for (int i = 0; i < lottery.Length; i++)
{
// ..
if (x == number)
{
counter++;
break;
}
// ..
}
Console.WriteLine("You have " + counter + " matches");
i have written a small program to print out the sum of the 1000 first primes, but for some reason i get the wrong result.
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
long sum;
sum = 0;
int count;
count = 0;
for (long i = 0; count <= 1000; i++)
{
bool isPrime = true;
for (long j = 2; j < i; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
sum += i;
count++;
}
}
Console.WriteLine(string.Format("{0}",sum));
Console.ReadLine();
}
}
}
result = 3674995 expected = 3682913
The implementation is identifying 1 as a prime, which is not correct; this can be fixed by initializing isPrime as follows.
bool isPrime = i != 1;
This yields the desired result 3682913; however the summand of 0 is also taken into account.
An efficient implementation checks for just prime divisors up to square root of the value; please, notice that all even values are not primes (with only exception - 2):
int count = 1000;
List<long> primes = new List<long>(count) {
2 }; // <- the only even prime
for (long value = 3; primes.Count < count; value += 2) {
long n = (long) (Math.Sqrt(value) + 0.1);
foreach (var divisor in primes)
if (divisor > n) {
primes.Add(value);
break;
}
else if (value % divisor == 0)
break;
}
// 3682913
Console.WriteLine(string.Format("{0}", primes.Sum()));
Console.ReadLine();
Try count = 1000000 and you'll get 7472966967499
long sum;
sum = 0;
int count;
count = 0;
for (long i = 0; count <= 1000; i++)
{
if (i == 1) continue;
bool isPrime = true;
for (long j = 2; j < i; j++)
{
if (i != j && i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
sum += i;
count++;
}
}
Console.WriteLine(string.Format("{0}", sum));
Console.ReadLine();
Here is a snippet from my code. Basically once the button is clicked this logic should fire out and determine if the number is prime or not. The problem is that some numbers are returning as "not prime", when in reality they are. Can anyone point out where the flaw is?
Thank you
private void bntTestPrime_Click(object sender, EventArgs e)
{
int num;
double num_sqrt;
int num_fl;
num = Convert.ToInt32(txtInput.Text);
num_sqrt = Math.Sqrt(num);
num_fl = Convert.ToInt32(Math.Floor(num_sqrt));
for (int i = 1; i <= num_fl; i++)
{
if (num % i == 0 && i != num)
lblResult_prime.Text = "Number " + num + " is not Prime.";
else
lblResult_prime.Text = "Number " + num + " is Prime.";
}
}
To add to Blender's answer, I'd like to point out that you're simply setting the output text on every iteration loop. That means your result will only depend upon the last number checked. What you need to do is assume the number is prime and loop through until a divisor is found. If a divisor is found. The number is prime if and only if no divisors are found. In the end the code should look something like this:
private bool IsPrime(int num)
{
double num_sqrt = Math.Sqrt(num);
int num_fl = Convert.ToInt32(Math.Floor(num_sqrt));
for (int i = 2; i <= num_fl; i++)
{
if (num % i == 0)
{
return false;
}
}
return true;
}
private void bntTestPrime_Click(object sender, EventArgs e)
{
int num = Convert.ToInt32(txtInput.Text);
bool isPrime = IsPrime(num);
if (isPrime)
lblResult_prime.Text = "Number " + num + " is Prime.";
else
lblResult_prime.Text = "Number " + num + " is not Prime.";
}
1 is a factor of every number, so you shouldn't check it. Start at 2. Also, you're already looping from 2 to sqrt(num), so there's no way for i to be equal to num.
You can decrease the performance hit on checking large numbers by using a conditional to check the first 4 primes, then start the loop at 11 and increment by 2. Something like this:
private bool IsPrime(int num)
{
double num_sqrt = Math.Sqrt(num);
int num_fl = Convert.ToInt32(Math.Floor(num_sqrt));
if (num !=1 && num !=2 && num != 3 && num != 5 && num != 7 && num % 2 > 0 _
&& num % 3 > 0 && num % 5 > 0 && num % 7 > 0)
{
for (int i = 11; i <= num_fl; i+=2)
{
if (num % i == 0)
{
return false;
}
}
}
else
return false;
return true;
}
You can shorten your code and increase the performance tremendously by using a List of primes that go big enough to cover the upper limit you want to check. Then use the Contains method to test for prime.
Try the code below.
bool IsPrime(int number) {
if(number%2==0 && number!=2) return false; //no need to check for even numbers
for (int i = 2; i < number; i++) {
if (number % i == 0 && i != number) return false;
}
return true;
}
Try this code below:
bool isPrimeNubmer(int n)
{
if (n >=0 && n < 4) //1, 2, 3 are prime numbers
return true;
else if (n % 2 == 0) //even numbers are not prime numbers
return false;
else
{
int j = 3;
int k = (n + 1) / 2 ;
while (j <= k)
{
if (n % j == 0)
return false;
j = j + 2;
}
return true;
}
}
public class PrimeChecker
{
public static bool Prime(int m)
{
for (int i =2; i< m; i++)
{
if (m % i ==0)
{
return false ;
}
}
return true;
}
public static void Main()
{
Console.WriteLine(Prime(13));
}
}