Can that be done with no while loops?
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(" #" + Fibonacci(number));
}
public static int Fibonacci(int number)
{
if (number <= 1)
{
return 1;
}
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}
I can't even add a Console.WriteLine in the body of base case since it gets executed [number] number of times; Not sure how to do this without loops...
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
Fibonacci(0, 1, 1, number);
}
public static void Fibonacci(int a, int b, int counter, int number)
{
Console.WriteLine(a);
if (counter < number) Fibonacci(b, a+b, counter+1, number);
}
public static int Fibonatchi(int position) {
if(position == 0) {
return 1;
}
if(position == 1) {
return 1;
} else {
return Fibonatchi(position - 2) + Fibonatchi(position - 1);
}
}
I didn't find a way to do it closest way is it to combine both loops + recursion
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
int number = Convert.ToInt32(Console.ReadLine());
for(int counter=0;counter<number;counter++)
Console.WriteLine(" \n" + Fibonacci(counter) );
}
public static int Fibonacci(int number)
{
if (number == 0)
return 0;
else if(number ==1)
return 1;
else
{
return Fibonacci(number - 2) + Fibonacci(number - 1);
}
}
namespace Algorithms
{
class Program
{
static void Main(string[] args)
{
string fibResult = "";
fibResult = FibCal(10);
Console.WriteLine(fibResult);
Console.ReadLine();
}
public static string FibCal(int n)
{
string series = "";
int k, f1, f2 , f = 0;
f1 = f2 = 1;
if (n < 2)
return n.ToString();
else
for (k = 0; k < n; k++)
{
f = f1 + f2;
f2 = f1;
f1 = f;
series += f.ToString() + ",";
}
return series;
}
}
}
Hope this helps
Using recursion in this fashion is a very bad idea. It will cause memory problems very quickly. I know you want to avoid using while/for loops, but an array is really the best way to go.
Using LINQ
public static void fibSeriesEx3()
{
List<int> lst = new List<int> { 0, 1 };
for (int i = 0; i <= 10; i++)
{
int num = lst.Skip(i).Sum();
lst.Add(num);
foreach (int number in lst)
Console.Write(number + " ");
Console.WriteLine();
}
}
That's a way to do it by returning a value into the main.
public static void Main() {
Console.WriteLine("Introduce the number");
int num = Convert.ToInt32(Console.ReadLine());
int num1 = 1, num2 = 1, counter = num-2;
//Take 2 out to match the list as first 2 numbers doesn't count in the function.
Console.WriteLine(Fibo(num1, num2, counter));
}
public static int Fibo(int num1, int num2, int counter) {
int temp = num1;
if (counter <= 0)
return num2;
else
return Fibo(num1 = num2, num2 += temp, counter-1);
}
public static class Golden
{
public static IEnumerable<long> Fibonacci()
{
var a = 0L;
var b = 1L;
var s = 0L;
yield return a;
while (a < long.MaxValue - b)
{
yield return b;
s = a + b;
a = b;
b = s;
}
}
public static IEnumerable<long> FibonacciR()
{
IEnumerable<long> Fibo(long a, long b)
{
yield return a;
if (a < long.MaxValue - b)
{
foreach (var v in Fibo(b, a + b))
{
yield return v;
}
}
}
return Fibo(0, 1);
}
}
I realize this may be an old thread, but oh well I think this kinda question is good in its nature.
Using while loop/or recursive way of doing is not the optimal way of doing as it takes a O(2^n) times. A better way to do this is using what is already in memory like below. This should take at most O(n) time.
Cheers!
static double fibDynamic(int n)
{
double[] array = new double[n];
array[0] = array[1] = 1;
for(int i = 2; i < n; i++)
{
array[i] = array[i - 1] + array[i - 2];
}
return array[n-1];
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int Main(string[] args)
{
int n, i = 0, c;
Console.WriteLine("Enter the number of terms:");
n = Convert.ToInt16(Console.ReadLine());
Console.WriteLine("Fibonacci series\n");
for (c = 1; c <= n; c++)
{
int result = FibonacciFunction(i);
Console.Write(result + " " );
i++;
}
Console.WriteLine();
return 0;
}
public static int FibonacciFunction(int n)
{
if (n == 0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return (FibonacciFunction(n - 1) + FibonacciFunction(n - 2));
}
}
}
}
Simple and easy solution :
static void Main(string[] args)
{
int number;
Console.WriteLine("enter number");
number = int.Parse(Console.ReadLine());
Console.WriteLine(Recursive(number));
Console.ReadLine();
}
public static int Recursive(int number)
{
if (number <= 2)
{
return 1;
}
else
{
return Recursive(number - 1) + Recursive(number - 2);
}
}
Using one line code:
public static int Fibonacci(int i)
{
return i <= 2 ? 1 : Fibonacci(i - 1) + Fibonacci(i - 2);
}
Related
I'm trying to get the job done MOHIBPIZ - PIZZA (https://www.spoj.com/problems/MOHIBPIZ/).
I'm already sitting on it the second day, I've tried everything I can and found on the internet. The last chance before giving up is to ask you guys
For recudces time I'm using InputOutput class created by davidsekar (https://github.com/davidsekar/C-sharp-Programming-IO/blob/master/ConsoleInOut/InputOutput.cs)
but still I have time "time limit exceeded". :(
I tried with two loops, but the method with the function seems more optimal to me. Thanks in advance for all the hints, suggestions and answers.
This is code (link on ideone: https://ideone.com/):
using System;
using System.IO;
public class Test
{
public static void Main()
{
InputOutput reader = new InputOutput();
StreamWriter _output = new StreamWriter(Console.OpenStandardOutput());
int T = reader.ReadInt();
for (int i = 0; i < T; i++)
{
_output.WriteLine(Recursion(reader.ReadInt()));
}
_output.Flush();
}
private static int Recursion(int x)
{
if(x <= 1)
{
return 2;
}
else
{
return Recursion(x - 1) + x;
}
}
#region Input Output Helper
public class InputOutput : System.IDisposable
{
private System.IO.Stream _readStream, _writeStream;
private int _readIdx, _bytesRead, _writeIdx, _inBuffSize, _outBuffSize;
private readonly byte[] _inBuff, _outBuff;
private readonly bool _bThrowErrorOnEof;
public void SetBuffSize(int n)
{
_inBuffSize = _outBuffSize = n;
}
public InputOutput(bool throwEndOfInputsError = false)
{
_readStream = System.Console.OpenStandardInput();
_writeStream = System.Console.OpenStandardOutput();
_readIdx = _bytesRead = _writeIdx = 0;
_inBuffSize = _outBuffSize = 1 << 22;
_inBuff = new byte[_inBuffSize];
_outBuff = new byte[_outBuffSize];
_bThrowErrorOnEof = throwEndOfInputsError;
}
public void SetFilePath(string strPath)
{
strPath = System.IO.Path.GetFullPath(strPath);
_readStream = System.IO.File.Open(strPath, System.IO.FileMode.Open);
}
public T ReadNumber<T>()
{
byte rb;
while ((rb = GetByte()) < '-')
;
var neg = false;
if (rb == '-')
{
neg = true;
rb = GetByte();
}
dynamic m = (T)Convert.ChangeType(rb - '0', typeof(T));
while (true)
{
rb = GetByte();
if (rb < '0')
break;
m = m * 10 + (rb - '0');
}
return neg ? -m : m;
}
public int ReadInt()
{
byte readByte;
while ((readByte = GetByte()) < '-')
;
var neg = false;
if (readByte == '-')
{
neg = true;
readByte = GetByte();
}
var m = readByte - '0';
while (true)
{
readByte = GetByte();
if (readByte < '0')
break;
m = m * 10 + (readByte - '0');
}
return neg ? -m : m;
}
public string ReadString()
{
return ReadString(' ');
}
public string ReadString(string delimiter)
{
return ReadString(delimiter[0]);
}
public string ReadString(char delimiter)
{
byte readByte;
while ((readByte = GetByte()) <= delimiter)
;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
do
{
sb.Append((char)readByte);
} while ((readByte = GetByte()) > delimiter);
return sb.ToString();
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
private byte GetByte()
{
if (_readIdx >= _bytesRead)
{
_readIdx = 0;
_bytesRead = _readStream.Read(_inBuff, 0, _inBuffSize);
if (_bytesRead >= 1)
return _inBuff[_readIdx++];
if (_bThrowErrorOnEof)
throw new System.Exception("End Of Input");
_inBuff[_bytesRead++] = 0;
}
return _inBuff[_readIdx++];
}
public void WriteToBuffer(string s)
{
foreach (var b in System.Text.Encoding.ASCII.GetBytes(s))
{
if (_writeIdx == _outBuffSize)
Flush();
_outBuff[_writeIdx++] = b;
}
}
public void WriteLineToBuffer(string s)
{
WriteToBuffer(s);
if (_writeIdx == _outBuffSize)
Flush();
_outBuff[_writeIdx++] = 10;
}
public void WriteToBuffer(int c)
{
byte[] temp = new byte[10];
int tempidx = 0;
if (c < 0)
{
if (_writeIdx == _outBuffSize)
Flush();
_outBuff[_writeIdx++] = (byte)'-';
c = -c;
}
do
{
temp[tempidx++] = (byte)((c % 10) + '0');
c /= 10;
} while (c > 0);
for (int i = tempidx - 1; i >= 0; i--)
{
if (_writeIdx == _outBuffSize)
Flush();
_outBuff[_writeIdx++] = temp[i];
}
}
public void WriteLineToBuffer(int c)
{
WriteToBuffer(c);
if (_writeIdx == _outBuffSize)
Flush();
_outBuff[_writeIdx++] = 10;
}
private void Flush()
{
_writeStream.Write(_outBuff, 0, _writeIdx);
_writeStream.Flush();
_writeIdx = 0;
}
public void Dispose()
{
Flush();
_writeStream.Close();
_readStream.Close();
}
}
#endregion Input Output Helper
}
As far as I can see, you have a well known Circle Division problem; see also A000124 sequence:
number of pieces after n cuts are (n * n + n + 2) / 2
That's why we can put O(1) time and space complexity
Code:
private static int Solution(int n) => (int)(((long)n * n + n + 2) / 2);
Here I've put (long) n in case n * n exceeds int.MaxValue, when (n * n + n + 2) / 2 doesn't.
Edit: I've implemented int Solution(int n) method which is based on current code int Recursion(int x) signature; but if there're tests for large n we are going to have integer overflow.
In this case
private static long Solution(long n) =>
1 + (n % 2 == 0 ? n / 2 * (n + 1) : (n + 1) / 2 * n);
In case of arbitrary n we have to use BigInteger:
using System.Numerics;
...
private static BigInteger Solution(BigInteger n) =>
1 + (n * n + n) / 2;
An anagram is a word formed from another by rearranging its letters, using all the original letters exactly once; for example, orchestra can be rearranged into carthorse.
I want to write a function to return all anagrams of a given word (including the word itself) in any order.
For example GetAllAnagrams("abba") should return a collection containing "aabb", "abab", "abba", "baab", "baba", "bbaa".
Any help would be appreciated.
Here is a working function, making use of a GetPermutations() extension found elsewhere on stack overflow
public static List<string> GetAnagrams(string word)
{
HashSet<string> anagrams = new HashSet<string>();
char[] characters = word.ToCharArray();
foreach (IEnumerable<char> permutation in characters.GetPermutations())
{
anagrams.Add(new String(permutation.ToArray()));
}
return anagrams.OrderBy(x => x).ToList();
}
Here is the GetPermutations() extension and it's other necessary extensions:
public static IEnumerable<IEnumerable<T>> GetPermutations<T>(this IEnumerable<T> enumerable)
{
var array = enumerable as T[] ?? enumerable.ToArray();
var factorials = Enumerable.Range(0, array.Length + 1)
.Select(Factorial)
.ToArray();
for (var i = 0L; i < factorials[array.Length]; i++)
{
var sequence = GenerateSequence(i, array.Length - 1, factorials);
yield return GeneratePermutation(array, sequence);
}
}
private static IEnumerable<T> GeneratePermutation<T>(T[] array, IReadOnlyList<int> sequence)
{
var clone = (T[])array.Clone();
for (int i = 0; i < clone.Length - 1; i++)
{
Swap(ref clone[i], ref clone[i + sequence[i]]);
}
return clone;
}
private static int[] GenerateSequence(long number, int size, IReadOnlyList<long> factorials)
{
var sequence = new int[size];
for (var j = 0; j < sequence.Length; j++)
{
var facto = factorials[sequence.Length - j];
sequence[j] = (int)(number / facto);
number = (int)(number % facto);
}
return sequence;
}
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
private static long Factorial(int n)
{
long result = n;
for (int i = 1; i < n; i++)
{
result = result * i;
}
return result;
}
}
Here is a screenshot of the result:
And, finally, a github repository of the complete Visual Studio solution: Github
import java.util.Scanner;
import java.lang.String;
public class KrishaAnagram
{
public static void main(String[] args) {
Scanner Scan = new Scanner(System.in);
String s1, s2;
int sum1, sum2;
sum1 = sum2 = 0;
System.out.print("Enter fisrt string: ");
s1 = Scan.next();
System.out.print("Enter Second string: ");
s2 = Scan.next();
if (s1.length() != s2.length()) {
System.out.println("NOT ANAGRAM");
} else {
for (int i = 0; i < s1.length(); i++) {
char ch1 = s1.charAt(i);
char ch2 = s2.charAt(i);
sum1 += (int) ch1;
sum2 += (int) ch2;
}
if (sum1 == sum2)
System.out.println("IT IS AN ANAGRAM : s1 = " + sum1 + "s1 = " + sum2);
else
System.out.println("IT IS NOT AN ANAGRAM : s1 = " + sum1 + "s1 = " + sum2);;
}
}
}
//This is My way of solving anagram in java,Hope it helps.
Recently I wondered what might be the smallest implementation of an IEumerable which returns a given number of prime numbers. It should fit in this program:
static int Main(string[] args)
{
while(true)
{
Console.WriteLine("How many Primes?");
string line = Console.ReadLine();
if (line.Trim() == "") break;
int numPrimes;
if(!int.TryParse(line.Trim(), out numPrimes)) continue;
int i = 1;
foreach(int p in PrimeNumbers(numPrimes))
{
Console.WriteLine("{0}: {1}", i++, p);
}
}
return 0;
}
My attempt looks like this:
static IEnumerable<int> PrimeNumbers(int numPrimes)
{
yield return 2; // first prime number
for(int n=1, p = 3; n < numPrimes; p+=2)
{
if (!checkIfPrime(p)) continue;
n++;
yield return p;
}
}
// p > 2, odd
private static bool checkIfPrime(int p)
{
for (int t = 3; t <= Math.Sqrt(p); t += 2)
{
if (p % t == 0) return false;
}
return true;
}
It is an Iterator which yield returns all the prime numbers.
Yet another example of smallest C# program:
static IEnumerable<int> PrimeNumbers(int n)
{
return Enumerable.Range(2, int.MaxValue - 2)
.Where(i => ParallelEnumerable.Range(2, Math.Max(0, (int)Math.Sqrt(i) - 1))
.All(j => i % j != 0))
.Take(n);
}
public static IEnumerable<int> PrimeNumbers(int NumberPrimes)
{
yield return 2;
for (int i = 3; i < NumberPrimes; i = i + 2)
{
bool IsPrime = true;
System.Threading.Tasks.Parallel.For(2, i, (o, state) =>
{
if (i % o == 0)
{
IsPrime = false;
state.Break();
}
});
if (IsPrime)
{
yield return i;
}
}
}
I am trying to write a program that will take the users input value and asks whether they want to calculate the value of the numbers 1 to n or the factorial of n!
This is what I have so far
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Project_2_Part_B
{
class Program
{
static void Main(string[] args)
{
var Fkeylow = "f";
var FkeyCap = "F";
var Skeylow="s";
var SkeyCap="S";
int n = 0;
long factorial = n;
Console.WriteLine("Input a value n");
n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Do you want to calculate factorial or sum");
Console.WriteLine("Enter F or S");
var A = Console.ReadLine();
if (A == Fkeylow)
Console.WriteLine();
if (A == FkeyCap)
Console.WriteLine();
var B=Console.ReadLine();
if (B == Skeylow)
Console.WriteLine();
if (B == SkeyCap)
Console.WriteLine();
Console.WriteLine("Press any key to close...");
Console.ReadLine();
}
}
}
My issue is with the syntax of the calculation to make the code execute the n*(n-1) while n>1.
static void Main(string[] args)
{
Console.WriteLine("Input a value n");
string number = Console.ReadLine(); // Read number
int n = Convert.ToInt32(number); // Converting to int
Console.WriteLine("Do you want to calculate factorial or sum? ");
Console.WriteLine("Enter F or S. ");
string choose = Console.ReadLine(); // F or S
int result = -1; // To view later
if (choose == "f" || choose == "F")
{
result = 1;
for (int i = n; i >= 1; i--) // Loop for calculating factorial
result *= i;
}
else if (choose == "s" || choose == "S")
{
result = 0;
for (int i = n; i >= 1; i--) // Loop for calculating sum
result += i;
}
Console.WriteLine(result); // Printing answer
Console.WriteLine("Press any key to close...");
Console.ReadLine();
}
Using recursion is another way of doing it:
static void Main(string[] args)
{
int n = 5;
Console.WriteLine(factorial(n));
Console.WriteLine(sum(n));
Console.Read();
}
public static int sum(int n)
{
if(n==0)
return 0;
return n+sum(n-1);
}
public static int factorial(int n)
{
if (n == 1)
return 1;
return n * factorial(n - 1);
}
Prints:
120 -->5!
15 -->1+2+3+4+5
Basic solution is here, tested,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication50
{
class Program
{
static void Main(string[] args)
{
NumberManipulator manipulator = new NumberManipulator();
Console.WriteLine("Factorial of six is :" + manipulator.factorial(16));
Console.ReadLine();
}
}
class NumberManipulator
{
public int factorial(int num)
{
int result=1;
int b = 1;
do
{
result = result * b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
Console.WriteLine(result);
b++;
} while (num >= b);
return result;
}
}
}
I'm having a logic problem here. I want to add the result of the factorial values but I'm not sure how to add them. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task_8_Set_III
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " +);
}
}
static double fact(double value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}
}
}
Not sure if this is what you meant but if for factorial of N you want to have the sum of all factorials up to that value this is how you do it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Task_8_Set_III
{
class Program
{
static void Main(string[] args)
{
double sum = 0;
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
sum += c;
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + sum);
}
}
static double fact(double value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}
}
}
You need to add a total variable to keep track of the sum.
double total = 0; //the total
for (int i = 1; i <= 7; i++)
{
double c = i / fact(i);
total += c; // build up the value each time
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + total);
}
short of totally understanding what you want to do exactly, here's two things...
in programming, the following expression is perfectly valid:
i = i + 1 Saying "the new value of i is the old value of i plus one"
variables live within scopes, their boundaries usually being braces { }, that is you will need a variable that is outside the braces of the foreach in order to "remember" stuff of the previous iteration.
static void Main(string[] args)
{
int sum = 0;
for (int i = 1; i <= 7; i++)
{
int c = fact(i);
sum += c;
Console.WriteLine("Factorial is : " + c);
Console.ReadLine();
Console.WriteLine("By Adding.. will give " + sum);
}
}
static int fact(int value)
{
if (value ==1)
{
return 1;
}
else
{
return (value * (fact(value - 1)));
}
}