i wanna ask something. My script gots some error
Here is it
using System;
namespace 3nplus1
{
class MainClass
{
public static void Main(string[] args)
{
Console.Write("Enter a number: ");
int n = Convert.ToInt32(Console.ReadLine());
while (Convert.ToBoolean(n = 1))
{
if (Convert.ToBoolean(n % 2 = 0))
{
n = n / 2;
Console.WriteLine(n);
}
else
{
n = 3*n + 1;
Console.WriteLine(n);
}
}
Console.WriteLine(n);
}
}
}
The error message says:"/Error CS0131: The left-hand side of an assignment must be a variable, property or indexer (CS0131) (3nplus1)
The error is located on the first "if" line
Please help.
Thanks and sorry for bad English.
You are confusing the = operator(assignment) with the == operator which is used for comparisons. So this is not a comparison that evaluates to true but an assignment(that returns the value that you assign).
if (Convert.ToBoolean(n % 2 = 0))
but the compiler complains about it because there must not be an expression on the left side of the assignment(like here) but a variable. You also don't need those Convert.ToBoolean.
Well, as said this is just a followup error. You want something like this:
Console.WriteLine("Enter a number(exit with q): ");
string input = Console.ReadLine();
while (!input.Equals("q", StringComparison.OrdinalIgnoreCase))
{
int n;
while (!int.TryParse(input, out n))
{
Console.WriteLine("Enter a valid integer");
input = Console.ReadLine();
}
int result = n % 2 == 0 ? n / 2 : 3 * n + 1;
Console.WriteLine(result);
input = Console.ReadLine();
}
change this part of your code
while (n != 1)
{
if (n % 2 == 0)
{
n = n / 2;
Console.WriteLine(n);
}
else
{
n = 3*n + 1;
Console.WriteLine(n);
}
}
A single = represents an assignment, however in your case you want to check for equality and therefore use the == operator. Doing this eliminates the need to use Convert.ToBoolean.
With an = you assign a value to a variable or a property. But you want to make a comparison on the equality and for that you take two ==.
And by the way you don't need Convert.ToBoolean. Just write:
if (n % 2 == 0)
{
...
}
Related
I am writing an application where each multiple of 4 and 6 is added to a total variable named answer.
I am receiving this error, "The name 'sum' does not exist in the current context" It is occurring at Console.WriteLine(sum);.
class Program
{
static void Main(string[] args, int answer)
{
//Local Variables
int i;
int total = 0;
//Initialize Console
Console.WriteLine("Enter a number to begin");
string input = Console.ReadLine();
//Create integer from string input
int number = int.Parse(input);
//For Loop Looking for Multiples
for (i = 0; i < number; i++)
{
if (i % 4 == 0 || i % 6 == 0)
{
int sum;
sum = total + i;
}
Console.WriteLine(sum);
}
}
}
You Have To Declare The Variable sum out of if statement because this variable known only in if statement when the code get out of if statement the program doesn't know sum...The program know sum only in if statement
Each local variable exists within its scope {...} where it's declared:
if (i % 4 == 0 || i % 6 == 0)
{ // <- Scope of sum begins here
int sum;
sum = total + i;
} // <- Scope of sum ends here
Console.WriteLine(sum); // <- sum doesn't exists here (out of scope)
Let's move sum declaration out of the if and loop (in order to declare sum in a wider scope):
//DONE: , int answer dropped
static void Main(string[] args)
{ // <- now sum scope begins here
...
int sum = 0;
for (i = 0; i < number; i++)
{
if (i % 4 == 0 || i % 6 == 0)
{
//DONE: you probably want to add i to sum, not to total
sum = sum + i;
}
Console.WriteLine(sum);
}
} // <- sum scope ends here
In this case, you face such error because sum is declared inside if scope and it is not visible outside. You should move sum variable declaration out of if scope to make it visible for Console.WriteLine(...) method.
But as you mentioned, you just need to store a total number. So you don't even need sum variable here because you have total variable.
So let's rewrite this code like that:
class Program
{
static void Main(string[] args, int answer)
{
//Local Variables
int i;
int total = 0;
//Initialize Console
Console.WriteLine("Enter a number to begin");
string input = Console.ReadLine();
//Create integer from string input
int number = int.Parse(input);
//For Loop Looking for Multiples
for (i = 0; i < number; i++)
{
if (i % 4 == 0 || i % 6 == 0)
{
total += i;
}
Console.WriteLine(total);
}
}
}
For my C# programming homework, we had to write a program that allows the user to input an integer and use a loop to print out the factors of that integer.
I got the program to output the integers.
The problem is, for example, when I enter in the integer "24", I want the output to be
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
but the output that comes out is
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24 and
I don't want the extra "and" at the end of my Factors List
Here is what my code looks like:
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
int a, b;
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
Console.Write(b + " ");
}
}
Console.ReadLine();
}
}
}
EDIT: The output has to be formatted as
1 and 2 and 3 and 4 and 6 and 8 and 12 and 24
or else I won't get credit for the assignment
You can enumerate factors, and then Join them with " and "
private static IEnumerable<int> Factors(int value) {
// Simplest, not that efficient
for (int i = 1; i <= value; ++i)
if (value % i == 0)
yield return i;
}
...
Console.Write(string.Join(" and ", Factors(24)));
Or you can add " and " before, not after printing factors (i)
int value = 24;
bool firstTime = true;
// Simplest, not that efficient
for (int i = 1; i <= value; ++i) {
if (value % i == 0) {
// print "and" before printing i
if (!firstTime)
Console.Write(" and ");
firstTime = false;
Console.Write(i);
}
}
How about adding the numbers to a List and printing after the loop:
int a, b;
a = int.Parse(Console.ReadLine());
var result = new List<int>();
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
result.Add(b);
}
}
Console.Write(string.Join(" and ", result));
static void Main(string[] args)
{
//get input from user
Console.WriteLine("Please enter your integer: ");
int a = int.Parse(Console.ReadLine());
//enumerate factors
var factors = Enumerable.Range(1, a)
.Where(i => a % i == 0).ToArray();
//join for nicely printed output
Console.Write(string.Join(" and ", factors));
Console.ReadLine();
}
I would recommend you to create a string and output that string becouse it allows you to do more things with it, then do something like this:
int a, b;
string x="";
Console.WriteLine("Please enter your integer: ");
a = int.Parse(Console.ReadLine());
for (b = 1; b <= a; b++)
{
if (a % b == 0)
{
x=x + b.toString() +" and";
}
}
if you know that always will be an "and" at the end you can simply do this
string x = x.Substring(0, x.Length - 3);
and then
Console.Write(x);
Console.ReadLine();
I am trying to "Find the 10001st prime number" as part of the Project Euler challenges and i have no idea why my code doesn't work. When I tested my isPrime() function, it succeeded in finding whether a number was prime, but my program returns 10200 as the 10001st prime. Why is this?
Here is My Code:
using System;
using System.Collections.Generic;
namespace Challenge_7
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Solution to Project Euler");
Console.WriteLine("Challenge 7 - Find the 10001st prime");
Console.WriteLine("\nProject Start:");
List<int> primes = new List<int>();
int number = 1;
while (primes.Count != 10001)
{
if (isPrime(number))
{
primes.Add(number);
Console.WriteLine(number);
}
number++;
}
Console.WriteLine("The 10001st prime is: {0}", primes[10000]);
Console.ReadLine();
}
private static bool isPrime(int n)
{
bool prime = true;
for (int i = 1; i <= Math.Ceiling(Math.Sqrt(n)); i++)
{
for (int j = 1; j <= Math.Ceiling(Math.Sqrt(n)); j++)
{
if (i * j == n)
{
prime = false;
}
}
}
return prime;
}
}
}
Here's a hint::
Imagine a number that is the product of 3 primes.
Lets say 3, 5, and 7 (or) 105;
sqrt(105) == 10.2 so ceiling is 11
There aren't two numbers less than 11 that multiply to 105.
So your algorithm would falsely return true!
Try Again! :-D
The problem is in you loops. Math.Ceiling(Math.Sqrt(10200)) is 101 and you need to check 102 * 100 = 10200 but your loops never reaches 102 and returns 10200 as prime!
You can use the code below for isPrime. It is exists in this link and I changed to C# for you:
private static bool isPrime(int n)
{
if (n <= 1)
return false;
else if (n <= 3)
return true;
else if (n % 2 == 0 || n % 3 == 0)
return false;
int i = 5;
while (i * i <= n)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
i += 6;
}
return true;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace nthPrimeNumber
{
class Program
{
static void Main(string[] args)
{
ulong starting_number = 1;
ulong last_number = 200000; //only this value needs adjustment
ulong nth_primenumber = 0;
ulong a;
ulong b;
ulong c;
for (a = starting_number; a <= last_number; a++)
{
b = Convert.ToUInt64(Math.Ceiling(Math.Sqrt(a)));
for (c = 2; c <= b; c++)
{
if (a == 1 || (a % c == 0 && c != b))
{
break;
}
else
{
if (c == b)
{
nth_primenumber = nth_primenumber + 1;
break;
}
}
}
if (nth_primenumber == 10001)
{
break;
}
}
Console.WriteLine(nth_primenumber + "st" + "prime number is " + a);
Console.ReadKey();
}
}
}
The program above generates prime numbers between 1 and 200000. The program counts the generated prime numbers and checks if the generated prime numbers are already 10001. The program prints the 10001st prime number. If the program doesn't show 10001st (or shows below 10001) in the console, it is because the value of the last_number is small -- then try to adjust the value of the last_number (make it bigger). In this program, I have already adjusted the value of the last_number and will print the 10001st prime number.
I'm having problems with a task. I need to find and alert the user if the number is prime or not.
Here is my code:
int a = Convert.ToInt32(number);
if (a % 2 !=0 )
{
for (int i = 2; i <= a; i++)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
}
else
{
Console.WriteLine("prime");
}
Console.WriteLine();
}
}
else
{
Console.WriteLine("not prime");
}
Console.ReadLine();
Where did I go wrong, and how can I fix it?
Prime numbers is divisible by 1 and themselves you will need to check if number has exactly two divisor starting from one till number then it is prime.
int devisors = 0;
for (int i = 1; i <= a; i++)
if (a % i == 0)
devisors++;
if (devisors == 2)
Console.WriteLine("prime");
else
Console.WriteLine("not prime");
You can skip one iteration as we know all whole numbers are divisible by 1 then you will have exactly on divisor for prime numbers. Since 1 has only one divisor we need to skip it as it is not prime. So condition would be numbers having only one divisor other then 1 and number should not be one as one is not prime number.
int devisors = 0;
for (int i = 2; i <= a; i++)
if (a % i == 0)
devisors++;
if (a != 1 && devisors == 1)
Console.WriteLine("prime");
else
Console.WriteLine("not prime");
You just printed prime or not prime, and continued with the loop, rather than stopping. The %2 check is not really needed. Modified appropriately:
int a = Convert.ToInt32(number);
bool prime = true;
if (i == 1) prime = false;
for (int i = 2; prime && i < a; i++)
if (a % i == 0) prime = false;
if (prime) Console.WriteLine("prime");
else Console.WriteLine("not prime");
Console.ReadLine();
public bool isPrime(int num)
{
for (int i = 2; i < num; i++)
if (num % i == 0)
return false;
return num == 1 ? false : true;
}
Presumably your code is outputting lots of messages, which seem jumbled and meaningless? There are 3 key issues:
You arn't breaking out of your for loop when you've decided it can't be prime
You are assuming it is prime when it might not be, see the comments in the code below.
You are comparing to a itself, and that will always be divisible by a, the <= in the for condition needs to be <
Code:
int a = Convert.ToInt32(number);
if (a % 2 != 0)
{
for (int i = 3 i < a; i += 2) // we can skip all the even numbers (minor optimization)
{
if (a % i == 0)
{
Console.WriteLine("not prime");
goto escape; // we want to break out of this loop
}
// we know it isn't divisible by i or any primes smaller than i, but that doesn't mean it isn't divisible by something else bigger than i, so keep looping
}
// checked ALL numbers, must be Prime
Console.WriteLine("prime");
}
else
{
Console.WriteLine("not prime");
}
escape:
Console.ReadLine();
As other have mentioned, you could only loop to the square root of the a, by per-evaluating the square root and replacing this line:
for (int i = 3 i < a; i += 2)
with this:
float sqrRoot = (Int)Math.Sqrt((float)a);
for (int i = 3 i <= sqrRoot; i += 2)
It is important to per-evaluate it else your program will run much slower, rather than faster, as each iteration will involve a square root operation.
If you don't like goto statements (I love goto statements), post a comment and I'll replace it will a breakout boolean (or see Dukeling's more recent answer).
I've done far too much prime checking.
I did this:
bool isPrime = true;
List<ulong> primes = new List<ulong>();
ulong nCheck, nCounted;
nCounted = 0;
nCheck = 3;
primes.Add(2);
for (; ; )
{
isPrime = true;
foreach (ulong nModulo in primes)
{
if (((nCheck / 2) + 1) <= nModulo)
{ break; }
if (nCheck % nModulo == 0)
{ isPrime = false; }
}
if (isPrime == true)
{
Console.WriteLine("New prime found: " + (nCheck) + ", prime number " + (++nCounted) + ".");
primes.Add(nCheck);
}
nCheck++;
nCheck++;
}
This is not EXACTLY what you are looking for though, so what I'd do is put this in a background worker, but with the list of ulongs as a concurrent list, or something that you can access in 2 threads. Or just lock the list while it's being accessed. If the prime hssn't been worked out yet, wait until it is.
Yet another optimized way is to use Sieve of Eratosthenes algorithm.
From Wikipedia
To find all the prime numbers less than or equal to a given integer n by Eratosthenes' method:
1. Create a list of consecutive integers from 2 to n: (2, 3, 4, ..., n).
2. Initially, let p equal 2, the first prime number.
3. Starting from p, count up in increments of p and mark each of these numbers greater than p itself in the list. These will be multiples of p: 2p, 3p, 4p, etc.; note that some of them may have already been marked.
4. Find the first number greater than p in the list that is not marked. If there was no such number, stop. Otherwise, let p now equal this number (which is the next prime), and repeat from step 3.
When the algorithm terminates, all the numbers in the list that are not marked are prime.
C# code
int[] GetPrimes(int number) // input should be greater than 1
{
bool[] arr = new bool[number + 1];
var listPrimes = new List<int>();
for (int i = 2; i <= Math.Sqrt(number); i++)
{
if (!arr[i])
{
int squareI = i * i;
for (int j = squareI; j <= number; j = j + i)
{
arr[j] = true;
}
}
for (int c = 1; c < number + 1; c++)
{
if (arr[c] == false)
{
listPrimes.Add(c);
}
}
}
return listPrimes.ToArray();
}
private static void checkpirme(int x)
{
for (int i = 1; i <= x; i++)
{
if (i == 1 || x == i)
{
continue;
}
else
{
if (x % i == 0)
{
Console.WriteLine(x + " is not prime number");
return;
}
}
}
Console.WriteLine(x + " is prime number");
}
where x is number to check it if prime or not
I am trying to write a method to calculate the sum of the odd numbers in all the numbers less than the given number. so eg. CalcOdd(7) would return 5 + 3 + 1 = 9. CalcOdd (10) would return 9 + 7 + 5 + 3 + 1 = 25 etc
The method needs to take in a number, subtract 1, then recursively work backwards adding all odd numbers until it reaches 0. This is what I have so far.
private static int CalcOdd(int n)
{
if (n <= 1)
return 1;
else
if (n % 2 == 0)
n--;
return n + CalcOdd(n - 2);
}
It doesn't work so well, it includes the number passed in in the addition which is not what I want. Can anyone suggest a better way of doing this ? I would also loke to be able to port the answer to work for even numbers and add the option to include the original passed in number in the answer.
Many thanks
Why would you use recursion here? Just loop; or better, figure out the math to do it in a simple equation...
The fact is that C# doesn't make for excellent deep recursion for things like maths; the tail-call isn't really there at the moment.
Loop approach:
private static int CalcOdd(int n)
{
int sum = 0, i = 1;
while (i < n)
{
sum += i;
i += 2;
}
return sum;
}
You could do this with recursion as you say, but if you wish to do it quicker, then I can tell you that the sum of the n first odd numbers is equal to n*n.
private static int CalcOdd(int n) {
if (n<=1)
return 0;
if (n%2 == 1)
n--;
int k = n/2;
return k*k;
}
The reason this works is:
Every even number is of the form 2k, and the odd number before it is 2k-1.
Because 2*1-1 = 1, there are k odd numbers below 2k.
If n is odd, we don't want to include it, so we simply go down to the even number below it and we automatically have what we want.
Edited to fix broken code.
the sum of odd numbers less than a given number is a perfect square.
get the whole part of (n/2) to get the number of odd number less than itself.
square that and voila!
private static int CalcSumOdd(int n)
{
int i;
int.tryParse(n / 2, out i);
return i*i;
}
for even numbers its:
int i = n/2;
return i*(i+1);
correction. The above "even number sum" includes the original number "n". ie fn(12) = 42 = 2 + 4 + 6 + 8 + 10 + 12
if you want to exclude it, you should either unilaterally exclude it, or remove it with logic based on a passed in parameter.
Here is a correction,
int CalcOdd(int n)
{
n--; // <----
if (n <= 1)
return 0; // <----
else
if (n % 2 == 0)
n--;
return n + CalcOdd(n); // <----
}
i'm new here but this seems like a silly recursion exercise, given it can be done with a simple equation:
int sum(n,isEven,notFirst) {
int c=1; //skip the else
if (isEven) c=2;
if (notFirst) n-=2;
return ((n+c)*((n+c)/2))/2; }
classic discrete math sum series..
sum from 1 to 100 (odds and evens) is ((100+1)*(100/2))=5050
edit: in my code here, if you're calculating the sum of odds with n being even, or vice versa, it doesn't work, but i'm not going to put the work into that (and slop the code) right now. i'll assume your code will take care of that by the time it hits the function.. for example 7/2 isn't an int (obviously)
Why use recursion?
private Int32 CalcOdd(Int32 value)
{
Int32 r = 0;
{
while (value >= 1)
{
value--;
if (value % 2 != 0)
{
r += value;
}
}
}
return r;
}
Use a helper function. CalcOdd consists of testing n to see if it is even or odd; if it is even, return helper(n); if it is odd, return helper(n-2).
The helper function must handle three cases:
1) n is less than 1; in this case return 0.
2) n is even, in this case return helper(n-1).
3) n is odd, in this case return n+helper(n-1).
public static int CalcOdd(int n) {
// Find the highest even number. (Either n, or n-1.)
// Divide that by 2, and the answer should be the square of that number.
n = (n & 0x3FFFFFFE) >> 1;
return (int)Math.Pow(n, 2);
}
private static int CalcOdd(int n) {
n -= 1;
if ((n & 1) == 0) n--;
if (n <= 1) return 1;
return n + CalcOdd(n - 1);
}
But I would say doing loops is better and cleaner.
private static int CalcOdd(int n) {
int i, r = 1;
for (i = 3; i < n; i+=2)
r += i;
return r;
}
Since you want the option of including or excluding the first answer (and, keeping your "recursion" constraint in mind):
int calcOdd(int n, bool includeN)
{
if( !includeN )
return calcOdd(n-1, true);
if(n<=1)
return 1;
else
if(n%2 == 0)
n--;
return n+calcOdd(n-1, true);
}
The includeFirst, if passed as true, will include n in the calculations. Otherwise, the next layer down will start "including N".
Granted, as others have said, this is a horribly inefficient use of recursion, but... If you like recursion, try Haskell. It's a language built almost entirely on the concept.
int CalcOdd(int n)
{
n -= 1;
if (n <= 0)
return 0;
if (n % 2 == 0)
n--;
return n + CalcOdd(n);
}
This function is also recursive, and it has parameters which makes you able to decide wether to do even or odd number and wether you want to include the first number or not. If you are confused as to how it works, remember that bools also can be seen as 1 (true) and 0 (false)
int Calc(int n, bool even = false, bool includeFirst = false)
{
n -= !includeFirst;
if (n <= 0)
return 0;
if (n % 2 == even)
n--;
return n + Calc(n - includeFirst, even);
}
HÃ¥kon, I have ported your code to c# in VS 2008 as follows
static int Calc(int n, bool bEven, bool bIncludeFirst)
{
int iEven = Bool2Int(bEven);
int iIncludeFirst = Bool2Int(bIncludeFirst);
n -= 1 - iIncludeFirst;
if (n <= 0)
return 0;
if (n % 2 == iEven)
n--;
return n + Calc(n - iIncludeFirst, bEven, bIncludeFirst);
}
private static int Bool2Int(bool b)
{
return b ? 1 : 0;
}
It seems to be working. Now is there anything I can do to optomise ? i.e. I dont want to have to parse those bools to ints every time etc ?
I'd isolate the 'make it odd' part from the 'sum every other descending number' part: (forgive the Python)
def sumEveryTwoRecursive(n):
if n <= 0:
return 0
return n + sumEveryTwoRecursive(n - 2)
def calcOdd(n):
return sumEveryTwoRecursive(n - (2 if n % 2 else 1))
Just because there isn't one here yet, I've decided to use the LINQ hammer on this nail...
(borrowed from Nick D and Jason's pair programmed answer here)
void Main()
{
GetIterator(7, true, false).Sum().Dump();
// Returns 9
GetIterator(10, true, false).Sum().Dump();
// Returns 25
}
public IEnumerable<int> GetIterator(int n, bool isOdd, bool includeOriginal)
{
if (includeOriginal)
n++;
if (isOdd)
return GetIterator(n, 1);
else
return GetIterator(n, 0);
}
public IEnumerable<int> GetIterator(int n, int odd)
{
n--;
if (n < 0)
yield break;
if (n % 2 == odd)
yield return n;
foreach (int i in GetIterator(n, odd))
yield return i;
}
#include <iostream>
using namespace std;
int sumofodd(int num);
int main()
{
int number,res;
cin>>number;
res=sumofodd(number);
cout<<res;
return 0;
}
int sumofodd(int num)
{ if(num<1) return 0;
if (num%2==0) num--;
return num+sumofodd(num-1);
}