I need help implementing a for loop - c#

I've been trying to implement this into a for loop. I wrote out a flow chart for this program. The program needs to repeat until n = 1. Ive included a link to my flow chart. If someone could help me out here that would be awesome.
using System;
namespace collatzconjecture
{
class MainClass
{
public static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
if (n == 1)
{
Console.WriteLine("n = {0}", n);
}
else if (n % 2 == 0)
{
int a = n / 2;
Console.WriteLine("n = {0}", a);
}
else
{
int b = 3 * n + 1;
Console.WriteLine("n = {0}", b);
}
Console.ReadKey();
}
}
}

If you have to use for, put it straightforward, as it is described:
start with user input
break on n == 1
next step is either 3 * n + 1 or n / 2
something like this:
public static void Main(string[] args) {
for (int n = Convert.ToInt32(Console.ReadLine()); // start with user input
n > 1; // safier choice then n != 1
n = n % 2 == 0 ? n / 2 : 3 * n + 1) // next step either n/2 or 3*n + 1
Console.WriteLine(n);
Console.ReadKey();
}
However, if you can choose the implementation, I suggest extacting logic into a generator:
private static IEnumerable<int> Collatz(int n) {
while (n > 1) {
yield return n;
n = n % 2 == 0
? n / 2
: 3 * n + 1;
}
yield return n;
}
And UI
public static void Main(string[] args) {
int n = Convert.ToInt32(Console.ReadLine());
Console.Write(string.Join(Environment.NewLine, Collatz(n)));
}

What you really want is a while loop that continues until n is 1.
public static void Main(string[] args)
{
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("n = {0}", n);
while(n != 1)
{
if (n % 2 == 0)
{
n = n / 2;
}
else
{
n = 3 * n + 1;
}
Console.WriteLine("n = {0}", a);
}
Console.ReadKey();
}

Related

C# Collatz - Does anyone know a fix?

Hey does anyone have a fix for this? I don't know why i keep getting an error that the main-cs and compilation fails.
using System;
class MainClass {
public static void Main (string[] args) {
Console.WriteLine ("Length of Collatz Row");
int cn = Console.ReadLine();
CollatzListLength(cn);
}
public int CollatzListLength(n){
int number;
List<int> numbers = new List<int>();
while(n != 1){
if(n % 2 == 0){
number = n/2;
}
if(n%2 ==1){
number = n*3 + 1;
}
n = number;
numbers.Add(number);
}
return numbers.Count;
}
Console.ReadLine() returns a string, not an int.
CollatzListLength needs to be static and the parameter needs to be declared as int
n = number; doesn't work because number may never be assigned a value. Use else instead of if (n % 2 == 1) as it just checks the other possible condition anyway.
In total:
static void Main(string[] args)
{
Console.WriteLine("Length of Collatz Row");
if (int.TryParse(Console.ReadLine(), out int cn))
CollatzListLength(cn);
else
Console.WriteLine("Needs a number");
}
public static int CollatzListLength(int n)
{
int number;
List<int> numbers = new List<int>();
while (n != 1)
{
if (n % 2 == 0)
{
number = n / 2;
}
else
{
number = n * 3 + 1;
}
n = number;
numbers.Add(number);
}
return numbers.Count;
}
I haven't actually checked the sanity of the code though.
An alternative, repaired to compile without error messages:
using System;
using System.Collections.Generic;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Length of Collatz Row");
int cn = int.Parse(Console.ReadLine());
int len = CollatzListLength(cn);
Console.WriteLine($"len {len}");
}
public static int CollatzListLength(int n)
{
int number = 0;
List<int> numbers = new List<int>();
while (n != 1)
{
if (n % 2 == 0)
{
number = n / 2;
}
if (n % 2 == 1)
{
number = n * 3 + 1;
}
n = number;
numbers.Add(number);
}
return numbers.Count;
}
}

print pascal triangle values in a single loop

public void PrintPascalTriangle(int inNumberOfLines)
{
int noOfLines = inNumberOfLines;
int number = 1;
for(int i=0;i<noOfLines;i++)
{
number = 1;
for(int j=0;j<=i;j++)
{
Console.Write(number + " ");
number = number * (i - j) / (j + 1);
}
}
}
how can convert this method into single loop and print values in single row?
I just need Pascal triangle values in a row (no need to worry about spaces or visual rep) upto n.
Rows of Pascal's Triangle are all values of "the combinatorial function", n!/[k!( n-k)!], for a fixed n. The combinatorial function can be computed efficiently as below, see the Choose function, which I ripped from this answer:
class Program
{
static int Choose(int n, int k)
{
if (k > n)
return 0;
if (k * 2 > n)
k = n - k;
if (k == 0)
return 1;
int result = n;
for (int i = 2; i <= k; ++i)
{
result *= (n - i + 1);
result /= i;
}
return result;
}
static List<int> RowOfPascalsTriangle(int n)
{
return Enumerable.Range(0, n).Select(k => Choose(n-1, k)).ToList();
}
static void Main(string[] args)
{
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(1)));
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(2)));
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(3)));
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(4)));
Console.WriteLine(string.Join(" ", RowOfPascalsTriangle(5)));
}
}

C# (find second largest number) How to split program in subprograms ?so I can reuse code later...?

I have this program that finds second largest number from users input, user needs to input atleast 2 numbers and maximum 10. I want to split program into subprograms(at least main and one function). And i cant get it to work :(
Org. code:
static void Main(string[] args)
{
int n = 1, max = 0, smax = 0, i = 0, ISsmaxrepeating = 0;
while (n != 0 && i < 10)
{
Console.WriteLine("Input number");
n = int.Parse(Console.ReadLine());
//I want this part to be in a function from here.
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
//to here
if (n == smax)
{
ISsmaxrepeating = n; // checks if there are 2 numbers smax. Example: 2 1 1 it outputs error
}
i++;
}
if (smax != 0 && smax != ISsmaxrepeating)
{
Console.WriteLine("secondmax is {0}", smax);
}
else
{
Console.WriteLine("error");
}
Console.ReadLine();
So far I come up with this but it is not working :(
static int checking(int n, int max, int smax)
{
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
return n;
}
static void Main(string[] args)
{
int n = 1, max = 0, smax = 0, i = 0, ISsmaxrepeating = 0, result = 0;
while (n != 0 && i < 10)
{
Console.WriteLine("Input number");
n = int.Parse(Console.ReadLine());
result = checking(n,max,smax);
if (n == smax)
{
ISsmaxrepeating = n; // checks if there are 2 numbers smax. Example: 2 1 1 it outputs error
}
i++;
}
if (smax != 0 && smax != ISsmaxrepeating)
{
Console.WriteLine("secondmax is {0}", smax);
}
else
{
Console.WriteLine("error");
}
Console.ReadLine();
}
You can output multiple variables from the function using ref keyword. However, it's better not to use a function for this kind of operation.
static void checking(int n, ref int max, ref int smax)
{
if (n > max)
{
smax = max;
max = n;
}
else if (n > smax)
{
smax = n;
}
}
Call the function inside Main
checking(n, ref max, ref smax);
Why dont.you use Math.max or Math.min? If.you want to find highest between 3 numbes, first do int halfmax=math.max(firstnum,secondnum)
then do int max = Math.max(halfmaz,thirdnum).

Printing number sequence in C# with less loops

I am looking for a output below with the input n and with number of loops less than (n*(n+1))/2 ,
Example N = 4,
1
2 3
4 5 6
7 8 9 10
Number of loops should be less than 10.
Is this possible???
There's also a solution with only one loop.
Print numbers in order, followed by a space, and if the last number was triangular, then print a newline. Keep track of how many newlines you have, and that's it.
Here's the code:
public static void PrintPyramid(int n)
{
var i = 0;
while (n > 0)
{
Console.Write(++i);
if (IsTriangularNumber(i))
{
Console.Write(Environment.NewLine);
n--;
}
else
{
Console.Write(" ");
}
}
}
public static bool IsTriangularNumber(int i)
{
var n = (int)Math.Sqrt(i*2);
return n*(n + 1) / 2 == i;
}
And here's how it works: http://ideone.com/Mx7Cel
For faster triangular number tests, see the answers to this question.
By cheating it is easy:
public static void PrintPyramid(int n)
{
int i = 1;
int row = 1;
int maxNumberInRow = 1;
int cycles = 0;
while (row <= n)
{
cycles++;
if (i == maxNumberInRow)
{
Console.Write(i);
Console.Write(" ");
i++;
}
else
{
Console.Write(i);
Console.Write(" ");
i++;
Console.Write(i);
Console.Write(" ");
i++;
}
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
}
}
Console.WriteLine();
Console.WriteLine("Cycles: {0}", cycles);
}
I did a little loop unrolling, doing up to two numbers in the same cycle. For n == 4, it is 6 full cycles.
Note that if we want to play the semantic game, a partial loop unrolling is enough:
public static void PrintPyramid3(int n)
{
if (n >= 1)
{
Console.Write("1");
Console.Write(" ");
Console.WriteLine();
}
int i = 2;
int row = 2;
int maxNumberInRow = 3;
int cycles = 0;
while (row <= n)
{
cycles++;
Console.Write(i);
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
Console.WriteLine("Cycles: {0}", cycles);
}
The first row is "outside" the loop, so for n == 4, only 9 cycles are necessary.
Based on this code, it is easy to partially loop unroll the first x cases and do the remaining cases in a loop.
Ok... I was kidding... It is possible to do it in a totally loopless way...
public static void PrintPyramid(int n)
{
PrintPyramidRecursive(n, 1, 1, 1);
}
private static void PrintPyramidRecursive(int n, int i = 1, int row = 1, int maxNumberInRow = 1)
{
Console.Write(i);
Console.Write(" ");
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
if (row > n)
{
return;
}
}
PrintPyramidRecursive(n, i, row, maxNumberInRow);
}
You only need to use recursion! :-) :-) :-)
This one is a little more devious: no (apparent) cycles and no recursion:
public static void PrintPyramid5(int n)
{
int i = 1;
int row = 1;
int maxNumberInRow = 1;
ManualResetEvent mre = new ManualResetEvent(false);
Timer t = null;
TimerCallback tc = x =>
{
Console.Write(i);
Console.Write(" ");
i++;
if (i > maxNumberInRow)
{
Console.WriteLine();
row++;
maxNumberInRow += row;
if (row > n)
{
t.Dispose();
mre.Set();
}
}
};
t = new Timer(tc, null, 0, 1);
mre.WaitOne();
}
Simply put, the printing method is called by a Timer :-) So the loop is in the operating system. The printing method (tc) will clearly be called 10 times for n == 4.
You could pretend that string.Join() and Enumerable.Range() don't do any looping internally, and do it like this:
int n = 4;
for (int i = 1, j = 1; i <= n; ++i, j += i-1)
Console.WriteLine(string.Join(" ", Enumerable.Range(j, i).Select(x => x.ToString("00"))));
The for loop therefore only loops once per line rather than once per output number. But it's a cheat, because string.Join() and Enumerable.Range() do loop internally.
As per xanatos's suggestion, here's a version with no explicit loops at all:
Console.WriteLine(
string.Join("\n", Enumerable.Range(1, n).Select(i =>
string.Join(" ", Enumerable.Range((i*(i-1))/2+1, i).Select(x =>
x.ToString("00"))))));
This is a curiosity only, of course. ;)
Finally, here's a variant of xanatos's recursive solution:
private static string Triangular(int max, int row, int rowEnd, int number)
{
if (row == max)
return "";
else if (number <= rowEnd)
return number.ToString("00") + " " + Triangular(max, row, rowEnd, number + 1);
else
return "\n" + Triangular(max, row + 1, rowEnd + row + 1, number);
}
Which you'd use like this:
Console.WriteLine(Triangular(n, 1, 1, 1));
here i did your homework
public static void PrintPyramid(int n)
{
int t = 1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j <= i; j++)
{
Console.Write(t);
t++;
}
Console.WriteLine();
}
}

Number of zeroes at the end of factorial

I need to find the number of zeroes at the end of a factorial number. So here is my code, but it doesn't quite work :/
using System;
class Sum
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
long factoriel = 1;
for (int i = 1; i <= n; i++)
{
factoriel *= i;
}
Console.WriteLine(factoriel);
int timesZero = 0;
while(factoriel % 10 != 0)
{
timesZero++;
}
Console.WriteLine(timesZero);
}
}
I know I can use a for loop and divide by 5, but I don't want to. Where is the problem in my code and why isn't it working?
There's problem with your algorithm: integer overflow. Imagine, that you are given
n = 1000
and so n! = 4.0238...e2567; you should not compute n! but count its terms that are in form of (5**p)*m where p and m are some integers:
5 * m gives you one zero
25 * m gives you two zeros
625 * m gives you three zeros etc
The simplest code (which is slow on big n) is
static void Main(string[] args) {
...
int timesZero = 0;
for (int i = 5; i <= n; i += 5) {
int term = i;
while ((term % 5) == 0) {
timesZero += 1;
term /= 5;
}
}
...
}
Much faster implementation is
static void Main(string[] args) {
...
int timesZero = 0;
for (int power5 = 5; power5 <= n; power5 *= 5)
timesZero += n / power5;
...
}
Counting Trailing zeros in Factorial
static int countZerosInFactOf(int n)##
{
int result = 0;
int start = 1;
while (n >= start)
{
start *= 5;
result += (int)n/start;
}
return result;
}
Make sure to add inbuilt Reference System.Numeric
using System.Text;
using System.Threading.Tasks;
using System.Numeric
namespace TrailingZeroFromFact
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter a no");
int no = int.Parse(Console.ReadLine());
BigInterger fact = 1;
if (no > 0)
{
for (int i = 1; i <= no; i++)
{
fact = fact * i;
}
Console.WriteLine("{0}!={1}", no, fact);
string str = fact.ToString();
string[] ss = str.Split('0');
int count = 0;
for (int i = ss.Length - 1; i >= 0; i--)
{
if (ss[i] == "")
count = count + 1;
else
break;
}
Console.WriteLine("No of trailing zeroes are = {0}", count);
}
else
{
Console.WriteLine("Can't calculate factorial of negative no");
}
Console.ReadKey();
}
}
}
static void Main(string[] args)
{
Console.WriteLine("Enter the number:");
int n = int.Parse(Console.ReadLine());
int zero = 0;
long fac=1;
for (int i = 1; i <= n; i++)
{
fac *= i;
}
Console.WriteLine("Factorial is:" + fac);
ab:
if (fac % 10 == 0)
{
fac = fac / 10;
zero++;
goto ab;
}
else
{
Console.WriteLine("Zeros are:" + zero);
}
Console.ReadLine();
}
Your code seems fine, just a little correction in the while-condition:
public static int CalculateTrailingZeroes(BigInteger bigNum)
{
int zeroesCounter = 0;
while (bigNum % 10 == 0)
{
zeroesCounter++;
bigNum /=10;
}
return zeroesCounter;
}
That works, I just tested it.

Categories

Resources