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");
}
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 am trying to write a code that lists roots of given number.
This is what I did so far. The result I get is 2*2*5*5 which is true but I want to get this instead: 2^2*5^2.
public partial class Form1 : Form
{
List<int> divisor;
public Form1()
{
InitializeComponent();
}
private void list_Click(object sender, EventArgs e)
{
int number;
divisor = new List<int>();
showroot.Text = "";
number = Int32.Parse(usernum.Text);
for (int i = 2; i <= number; i++)
{
if (number % i == 0)
{
divisor.Add(i);
number = number / i;
i = 1;
}
}
for (int i = 0; i < divisor.Count; i++)
{
print(""+ divisor[i]);
}
}
private void print(String text)
{
if (showroot.Text != "")
{
showroot.Text = showroot.Text + "*" + text;
}
else
{
showroot.Text = text;
}
}
}
I tried to check how much same root and count them by two for statements nested but that brings another errors within.
for (int i = 0; i < divisor.Count; i++) {
for (int a = 0; i < divisor.Count; a++) {
if (i == a) {
base[i]++;
}
}
}
What to do?
Split the task into easy to implement portions, extract methods:
First of all, let's collect all prime divisors (divisors can repeat):
private static IEnumerable<int> AllPrimeDivisors(int value) {
if (value <= 1)
yield break;
for (; value % 2 == 0; value /= 2)
yield return 2;
int n = (int)(Math.Sqrt(value) + 0.5);
for (int d = 3; d <= n; d += 2) {
while (value % d == 0) {
yield return d;
value /= d;
n = (int)(Math.Sqrt(value) + 0.5);
}
}
if (value > 1)
yield return value;
}
Then combine them in required format (we should GroupBy the same - repeating - divisors and represent them either in divisor or in divisor^power format)
private static string Solve(int value) {
var terms = AllPrimeDivisors(value)
.GroupBy(divisor => divisor)
.Select(group => group.Count() == 1
? $"{group.Key}"
: $"{group.Key}^{group.Count()}");
return string.Join("*", terms);
}
Finally add UI:
private void list_Click(object sender, EventArgs e) {
if (int.TryParse(usernum.Text, out var number))
showroot.Text = Solve(number);
else
showroot.Text = "Incorrect Input, Syntax Error";
}
Tests:
int[] tests = new int[] {
3, 5, 9, 12, 16, 41, 81, 100,
};
var result = tests
.Select(item => $"{item,3} == {Solve(item)}");
Console.Write(string.Join(Environment.NewLine, result));
Outcome:
3 == 3
5 == 5
9 == 3^2
12 == 2^2*3
16 == 2^4
41 == 41
81 == 3^4
100 == 2^2*5^2
A naive implementation would be by changing your for to this:
for (int i = 2; i <= number; i++)
{
count = 0;
while (number % i == 0)
{
number = number / i;
count++;
}
if (count > 0)
{
divisor.Add(i);
powers.Add(count);
}
}
However a lot of optimizations can be done.
I have found a couple of topics related to this very problem, I just want to know why my code returns incorrect data.
So we have to find the first triangle number having more than 500 divisors. Details can be found here: http://projecteuler.net/problem=12
And here is my code:
Int64 triangularnum = 1;
for (Int64 num = 2; num > 0; num++)
{
if(has501Divisors(triangularnum))
{
MessageBox.Show(triangularnum.ToString());
break;
}
triangularnum += num;
}
private bool has501Divisors(Int64 candidate)
{
bool has501 = false;
int count = 0;
for (int i = 1; i < Math.Sqrt(candidate); i++)
{
if (candidate % i == 0) count += 1;
if (count > 501)
{
return true;
}
}
return has501;
}
This gives me number 842161320 which is apparently incorrect.
You should increment your count number by 2 not 1.
Also your
if (count > 501)
part is incorrect because your boundary should 500 not 501. Change it to count > 500 instead of.
static void Main(string[] args)
{
Console.WriteLine(Find());
}
public static int Find()
{
int number = 0;
for (int i = 1; ; i++)
{
number += i; // number is triangle number i
if (CountDivisorsOfNumber(number) > 500)
return number;
}
}
private static int CountDivisorsOfNumber(int number)
{
int count = 0;
int end = (int)Math.Sqrt(number);
for (int i = 1; i < end; i++)
{
if (number % i == 0)
count += 2;
}
if (end * end == number) // Perfect square
count++;
return count;
}
This prints 76576500 and looks like a right solution.
The problem is you are limiting your loop to the square root, which is smart, however that means you need to increment your count by two, not by 1 to account for both divisors.
Change your incrementation to this:
if (candidate % i == 0) count += 2;
Additionally, your count check checks for greater than 501 divisors, not 500.
Quick look but your check isn't ok:
if (count > 501)
This will stop at count 502, not 501.
for (int i = 1; i < Math.Sqrt(candidate); i++)
9 is divisible by 3, so you should use <= here. Also, you're divising by 1, you should start at i = 2.
I am trying the fizzbuzz program from here: Why Can't Programmers.. Program?
"Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"."
protected void btn1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 101; i++)
{
if (i % 3 == 0 & i % 5 == 0)
{
Response.Write("fizzbuzz" + ",");
}
else if (i % 3 == 0)
{
Response.Write("fizz" + ",");
}
else if (i % 5 == 0)
{
Response.Write("buzz" + ",");
}
else
{
i = i + 0;
}
Response.Write(i +",");
}
}
I am able to produce some kind of result like:
1,2,fizz,3,4,buzz,5,fizz,6,7,8,fizz,9,buzz,10,11,fizz,12,13,14,fizzbuzz,15,16,17,fizz,18,19,buzz,20,fizz,21,22,23,fizz,24,buzz,25,26,fizz,27,28,29,fizzbuzz,30,31,32,fizz,33,34,buzz,35,fizz,36,37,38,fizz,39, and so on..
The word fizz was printed but it did not replace 3 and fizzbuzz was printed but it did not replace 15 and so ...
Whether you hit the if condition or not you are still printing i at the end of your code.
Look specifically at your for loop:
for (int i = 1; i < 101; i++)
{
if (i % 3 == 0 & i % 5 == 0)
{
Response.Write("fizzbuzz" + ",");
}
else if (i % 3 == 0)
{
Response.Write("fizz" + ",");
}
else if (i % 5 == 0)
{
Response.Write("buzz" + ",");
}
else
{
i = i + 0;
}
Response.Write(i +","); //look here you print i
}
So you need to move that last Response.Write(i + ","); in the last else condition. The easiest way to find bugs like these is to use the debugger and debug your program. You will then easily see what the output is. So definately use the debugger and set breakpoints / watches and watch what happens. Your code should change to this:
for (int i = 1; i < 101; i++)
{
if (i % 3 == 0 & i % 5 == 0)
{
Response.Write("fizzbuzz" + ",");
}
else if (i % 3 == 0)
{
Response.Write("fizz" + ",");
}
else if (i % 5 == 0)
{
Response.Write("buzz" + ",");
}
else
{
Response.Write(i +","); //look here you print i
}
}
Notice the removal of i=i+1 your for loop is handling this already by incrementing i.
Edit Not sure if this is easier but here is another way to do this using lambda's:
List<int> t;
t = Enumerable.Range(1, 100).ToList();
var fizzBuzz = t.Where(num => num % 3 == 0 && num % 5 == 0);
var fizz = t.Where(num => num % 3 == 0);
var buzz = t.Where(num => num % 5 == 0);
var notFizzBuzz = t.Where(num => num % 3 != 0 && num % 5 !=0);
//print fizzBuzz elements
Console.WriteLine("Printing fizzBuzz elements...");
foreach (int i in fizzBuzz)
Console.WriteLine(i);
//print fizz elements
Console.WriteLine("Printing fizz elements...");
foreach (int i in fizz)
Console.WriteLine(i);
//print buzz elements
Console.WriteLine("Printing buzz elements...");
foreach (int i in buzz)
Console.WriteLine(i);
//print other elements
Console.WriteLine("Printing all others...");
foreach (int i in notFizzBuzz)
Console.WriteLine(i);
Try these changes
protected void btn1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 101; i++)
{
if (i % 3 == 0 & i % 5 == 0)
{
Response.Write("fizzbuzz" + ",");
}
else if (i % 3 == 0)
{
Response.Write("fizz" + ",");
}
else if (i % 5 == 0)
{
Response.Write("buzz" + ",");
}
else
{
Response.Write(i +",");
}
}
}
Your i = i + 0 obviously does nothing, since you are adding 0 to the value of i.
And you are printing the number to the response regardless of the result of the if/else block (it's put after it), so it should be moved into else (meaning only print if the if, or else if did not match.
move Response.Write(i +","); into your final else
protected void btn1_Click(object sender, EventArgs e)
{
for (int i = 1; i < 101; i++)
{
if (i % 3 == 0 & i % 5 == 0)
{
Response.Write("fizzbuzz" + ",");
}
else if (i % 3 == 0)
{
Response.Write("fizz" + ",");
}
else if (i % 5 == 0)
{
Response.Write("buzz" + ",");
}
else
{
i = i + 0; //this is totally useless
Response.Write(i + ",");
}
//Response.Write(i +","); //This will always write the number, even if you wrote fizz or buzz
}
}
Another simple implementation of it:
for (int i = 1; i <= 100; i++)
{
Console.WriteLine((i % 3 == 0) ? ((i % 5 == 0) ? "FizzBuzz" : "Fizz") : ((i % 5 == 0) ? "Buzz" : i.ToString()));
}
Console.ReadKey();
public static void PrintMod3And5FromInterval(int start, int end)
{
if (end < start)
{
Console.WriteLine("End number should be higher than start.");
}
else
{
string result = "";
for (int x = start; x <= end; x++)
{
if (x % 3 == 0)
result += "fizz";
if (x % 5 == 0)
result += "buzz";
if (result == "")
Console.WriteLine(x);
else
Console.WriteLine(result);
result = "";
}
}
}
static void Main(string[] args)
{
PrintMod3And5FromInterval(1, 100);
Console.Read();
}
Here was my original solution...
for (let number = 1; number <= 100; number ++) {
if (number % 3 === 0 && number % 5 === 0) {
console.log(number + "fizzbuzz");
} else if (number % 5 === 0) {
console.log(number + "buzz");
} else if (number % 3 === 0)
console.log(number + "fizz");
else {
console.log(number);
}
}
But this one is much shorter...
for (let n = 1; n <= 100; n++) {
let output = "";
if (n % 3 == 0) output += "Fizz";
if (n % 5 == 0) output += "Buzz";
console.log(output || n);
}