Calculate the stratified value of n+nn+nnn [duplicate] - c#

This question already has answers here:
"Error: Not all code paths return a value."
(7 answers)
Closed 1 year ago.
I tried to Write a console application that take a integer number from client and check if this number can be stratified, i.e. can be represented as
number = d + dd + ddd + ... + dd...ddd
where d is some digit. For instance
36 = 3 + 33
861 = 7 + 77 + 777
335 - can't be represent in d + dd + ddd
This is what Ido but I have an error “not all code path return a value”
using System;
namespace nn
{
class Program
{
static void Main(string[] args)
{
}
public static int N()
{
Console.WriteLine("Input integer");
//ask user to input integer
int n = int.Parse(Console.ReadLine());
for (int d = 1; d <= 9; d++)
{
var s = d;
var c = d;
while (s < n)
{
c = 10 * c + d; // generates dd, ddd, ...
s += c;
}
if (s == n)
{
return d;
}
else
{
return -1;
}
}
}
}
}

As error is self explanatory, Return type of function N() is int and your code is not returning integer after the for loop. To solve this issue, return integer after the closing bracket of for loop,
public static int N()
{
Console.WriteLine("Input integer");
//ask user to input integer
int n = int.Parse(Console.ReadLine());
for (int d = 1; d <= 9; d++)
{
var s = d;
var c = d;
while (s < n)
{
c = 10 * c + d; // generates dd, ddd, ...
s += c;
}
if (s == n)
{
return d;
}
else
{
return -1;
}
}
return -1; //This is missing return statement.
}

Related

ParameterizedThreadStart error, no overload for 'subroutine' matches delegate ParameterizedThreadStart

I am trying to create a thread which creates generates new RSA keys using my algorithm provided.
The algorithm may not be perfect but is fine by what i am doing - not the problem.
The problem lies with why doesnt the parts below work: from what i have gathered online i am using parameterizedthreadstart correctly?
Thread thread = new Thread(new ParameterizedThreadStart(GenerateKeys)); //issue here!!!!
thread.Start(RSA_KEYS, PublicKeysToDistribute);
it shows the error: no overload for 'GenerateKeys' matches delegate ParameterizedThreadStart.
Any help would be appreciated
static void Main(string[] args)
{
Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)> RSA_KEYS = new Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)>();
Queue<(BigInteger, BigInteger)> PublicKeysToDistribute = new Queue<(BigInteger, BigInteger)>();
Thread thread = new Thread(new ParameterizedThreadStart(GenerateKeys));
thread.Start(RSA_KEYS, PublicKeysToDistribute);
//recipitent receives public key in form e,n
//splits into Biginteger array : {e,n}
GenerateKeys(RSA_KEYS, PublicKeysToDistribute);
BigInteger[] PublicKey = Array.ConvertAll(PublicKeyRequest(PublicKeysToDistribute).Split(':'), BigInteger.Parse);
string input;
//creates message to encrypt
input = InputToAscii();
//encrypt using PublicKey
BigInteger a = encrypt(PublicKey, input);
BigInteger b = decrypt((RSA_KEYS[(PublicKey[0], PublicKey[1])]).Item1, (RSA_KEYS[(PublicKey[0], PublicKey[1])]).Item2, a);
Console.WriteLine(AsciiToOutput(b));
Console.ReadLine();
}
private static string PublicKeyRequest(Queue<(BigInteger, BigInteger)> PublicKeysToDistribute)
{
string publickey = PublicKeysToDistribute.Peek().Item1 + ":" +PublicKeysToDistribute.Peek().Item2;
PublicKeysToDistribute.Dequeue();
return publickey;
}
//create a key value pair where the publickey is key and private key is value
//publickey = {biginteger,biginteger} where {e,n}
//privatekey = {biginteger,biginteger} where {d,n}
public static void GenerateKeys(Dictionary<(BigInteger, BigInteger), (BigInteger, BigInteger)> RSA_KEYS, Queue<(BigInteger, BigInteger)> PublicKeysToDistribute)
{
int p = 4201; //default use 61 4201
int q = 4007; //default use 53 4007
int n = p * q;
// compute the totient, phi
int ϕn = (p - 1) * (q - 1);
//e for random number which 1 < e < ϕn and is co prime of ϕn
Random rn = new Random();
bool found = false;
BigInteger e = 0;
while (found == false)
{
e = rn.Next(1, ϕn);
if (Coprime(ϕn, e) == true)
{
break;
}
}
// where (d * e) mod ϕn = 1 find d
BigInteger d = 0;
for (int k = 1; k < ϕn; k++)
{
if ((k * e) % ϕn == 1)
{
d = k;
break;
}
}
Console.WriteLine("p="+p+",q="+q+",n="+n+",phi="+ϕn+",e="+e+",d="+d+",n="+n);
Console.WriteLine("Public key: e = " + e + " n = " + n);
Console.WriteLine("Private key: d = " + d + " n = " + n);
RSA_KEYS.Add((e, n), (d, n));
PublicKeysToDistribute.Enqueue((e, n));
Console.WriteLine("added new key to dictionary");
//return new KeyValuePair<(BigInteger, BigInteger), (BigInteger, BigInteger)>((e,n),(d,n));
}
private static BigInteger encrypt(BigInteger[] PublicKey, string input)
{
BigInteger m = BigInteger.Parse(input); //m = message
BigInteger c = eMod(m, PublicKey[0], PublicKey[1]); //cipher text = (message ^ e) mod n
return c;
}
private static BigInteger decrypt(BigInteger d, BigInteger n, BigInteger c)
{
BigInteger f = eMod(c, d, n); //result test = cipher ^ d mod n
return f;
}
private static BigInteger eMod(BigInteger a, BigInteger b, BigInteger c) //where a^b % c;
{
//base case
if (b == 0)
{
return 1;
}
else if (b % 2 == 0)
{
BigInteger d = eMod(a, b / 2, c);
//int result = d * d % c;
return ((d * d) % c);
}
else
{
return ((a % c) * eMod(a, b - 1, c)) % c;
}
}
private static BigInteger GetGCDByModulus(BigInteger value1, BigInteger value2)
{
while (value1 != 0 && value2 != 0)
{
if (value1 > value2)
value1 %= value2;
else
value2 %= value1;
}
return BigInteger.Max(value1, value2);
}
private static bool Coprime(BigInteger value1, BigInteger value2)
{
return GetGCDByModulus(value1, value2) == 1;
}
private static string InputToAscii()
{
Console.Write("Enter values to encrypt:");
char[] input = Console.ReadLine().ToCharArray(); //-1 < input < 999;
//char[] input = "-1".ToCharArray();
string AsciiInput = string.Empty;
for (int i = 0; i < input.Length; i++)
{
AsciiInput += ((int)input[i]).ToString();
}
Console.WriteLine(AsciiInput);
return AsciiInput;
}
private static string AsciiToOutput(BigInteger input)
{
string inputstring = input.ToString();
string output = string.Empty;
for (int i = 0; i < inputstring.Length / 2; i++)
{
output += (char)Convert.ToInt32((inputstring.Substring(i * 2, 2)));
}
return output;
}
}

Problem with prime numbers not printed correctly [duplicate]

This question already has answers here:
Check if number is prime number
(31 answers)
Closed 2 years ago.
I have a problem with my code and i don't know how to solve it. Basically this program prints prime numbers based on the user input and at the end it prints their sum. This works perfectly until a certain amount, example: if i input 10, it shows ten correct prime numbers, but if i input 100, it also prints a number that is not prime, in this case 533. I don't know where i'm wrong.
Thanks for the support.
EDIT: I solved it on my own. Basically there was an error in the first "If" inside the for loop, i've simply added "c = n - 1;" after n++. Now it works perfectly.
Console.Write("How many prime numbers?: ");
int l = Convert.ToInt32(Console.ReadLine());
int n = 2;
int sum = 0;
sum += n;
Console.WriteLine(n);
n++;
int i = 1;
l++;
while (i < l)
{
for (int c = n - 1; c > 1; c--)
{
if (n % c == 0)
{
n++;
}
else if (n % c != 0 && c == 2)
{
sum += n;
Console.WriteLine(n);
n++;
i++;
}
}
}
Console.WriteLine("Sum: " + sum);
Let's start from extracting method:
public static bool IsPrime(int value) {
if (value <= 1)
return false;
if (value % 2 == 0)
retutn value == 2;
int n = (int) (Math.Sqrt(value) + 0.5);
for (int d = 3; d <= n; d += 2)
if (value % d == 0)
return false;
return true;
}
Having this method implemented you can easily compute the sum of the first N primes:
int N = 100;
long s = 0;
for (int p = 1; N > 0; ++p) {
if (IsPrime(p)) {
s += p;
N -= 1;
}
}
Console.Write(s);
Another (a bit more complex) possibility is prime numbers enumeration:
public static IEnumerable<long> Primes() {
yield return 2;
List<int> knownPrimes = new List<int>();
for (int p = 3; ; p += 2) {
int n = (int) (Math.Sqrt(p) = 0.5);
bool isPrime = true;
foreach (int d in knownPrimes) {
if (d > n)
break;
if (p % n == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
knownPrimes.Add(p);
yield return p;
}
}
}
Then you can query enumeration with a help of Linq:
using System.Linq;
...
long s = Primes()
.Take(N)
.Sum();

How do you leave roots in surd form in c#?

Example a: √12 =2√3
Example b: √16 = 4
I am trying to get both.
Whilst I can of course use Math.Sqrt(4) to achieve outcome b, I've no idea how to achieve a, or further how to get both to work simultaneously which is the goal. How do I achieve this type of simplification in C#?
I have tried several libraries including MathNet, Symbolics and NCalc with no success.
This post may have solved it in c++, although I do not know for sure. My attempts at converting that solution to even see if it worked were very much a failure:
var outside_root = 1;
var inside_root = 800;
var d = 2;
while (d * d <= inside_root)
if (inside_root % (d * d) == 0) //# inside_root evenly divisible by d * d
{
inside_root = inside_root / (d * d);
outside_root = (outside_root * d);
}
while (d * d > inside_root) {
d = (d + 1);}
Thank you for any help
The given C++ can be translated into C# without a lot of changes. Also a couple of modifications can be made to the original algorithm to reduce number of multiplications and increase overall performance:
static (int, int) Sqrt2(int n)
{
int m = 1, d = 2;
int dSquared;
while ((dSquared = d * d) <= n)
{
while ((n % dSquared) == 0)
{
n /= dSquared;
m *= d;
}
d++;
}
return (m, n);
}
static void Main(string[] args)
{
Console.WriteLine(Sqrt2(12)); // prints (2, 3)
Console.WriteLine(Sqrt2(16)); // prints (4, 1)
Console.WriteLine(Sqrt2(13)); // prints (1, 13)
}
This could be one of the solution
I think this is efficient. I used it in my calculator app
I did that using java. Hope this will help
static void surd_form(long a) {
long i = 2;
long sq = 1;
long k = 4;
long p = 1;
while (k <= a) {
if (a % i == 0) {
if (a % k == 0) {
a /= k;
sq *= i;
} else {
a /= i;
p *= i;
}
} else {
i += 1;
}
k = i * i;
}
System.out.println(sq + "" + "√" + (a * p));
}

Custom number system in C# [duplicate]

This question already has answers here:
How to convert a column number (e.g. 127) into an Excel column (e.g. AA)
(60 answers)
Closed 5 years ago.
I have a requirement for a custom number system in C# which goes as following:
A - 1
B - 2
...
Z - 26
AA - 27
AB - 28
I've made a function that converts from arbitrary strings to numbers like this:
private const int Min = 'A';
private const int Max = 'Z';
private const int Base = Max - Min + 1;
private static int GetCharValue(char c)
{
if (c < Min || c > Max)
throw new ArgumentOutOfRangeException(nameof(c), c, $"Character needs to be between '{Min}' and '{Max}', was '{c}'.");
return c - Min + 1;
}
public static int GetStringValue(string s)
{
char[] chars = s.ToCharArray();
int[] values = new int[chars.Length];
for (var i = 0; i < chars.Length; i++)
{
values[i] = GetCharValue(chars[i]);
}
int position = 1;
int value = 0;
for (var i = values.Length - 1; i >= 0; i--)
{
value += position * values[i];
position *= Base;
}
return value;
}
I've tested it to be working for up to AAA (not rigorously, just skimming over the output of printing them all). However, I can't for the life of me figure out how to write the reverse function. In other words, I need 1 to return A, 26 to return Z and 27 to return AA. The "problem" is that this number system has no 0, so it doesn't easily convert to any base. For instance, if A was 0, then AA would also be 0, but it's not. So how do I solve this?
you can simply generate it like this....
public static IEnumerable<string> generate()
{
long n = -1;
while (true) yield return toBase26(++n);
}
public static string toBase26(long i)
{
if (i == 0) return ""; i--;
return toBase26(i / 26) + (char)('A' + i % 26);
}
public static void BuildQuery()
{
IEnumerable<string> lstExcelCols = generate();
try
{
string s = lstExcelCols.ElementAtOrDefault(1) ;
}
catch (Exception exc)
{
}
}

Find the nth element in a tribonacci series

I found this as a Microsoft interview question (see Round 4). I am trying to solve it using C#. My attempt:
private static int NTerm_Tribonacci(int term)
{
int a = 0;
int b = 1;
int c = 1;
int result = 0;
if (term == 1) return a;
if (term == 2) return b;
if (term == 3) return c;
for (int i = 4; i <= term; i++)
{
a = a + b + c; if ((1 + 3 * i) % term == 0) { result = a; break; }
b = a + b + c; if ((2 * i + i - 1) % term == 0) { result = b; break; }
c = a + b + c; if ((3 * i) % term == 0) { result = c; break; }
}
return result;
}
But it is somehow not working var res = NTerm_Tribonacci(5);//should be 4 but getting 44
How can I solve this?
Tribonacci Number
Try this:
private static int NTerm_Tribonacci(int term)
{
int a = 0;
int b = 1;
int c = 1;
int result = 0;
if (term == 0) result = a;
if (term == 1) result = b;
if (term == 2) result = c;
while(term > 2)
{
result = a + b + c;
a = b;
b = c;
c = result;
term--;
}
return result;
}
Note that as per the definition in your link, I have assumed the first term to be T0, not T1.
Demo
I like the "LINQ way" of solving such things:
public IEnumerable<long> InfiniteTribonacciSequence()
{
long a = 0, b = 1, c = 1;
long nextTerm;
yield return a;
yield return b;
yield return c;
while (true)
{
nextTerm = a + b + c;
yield return nextTerm;
a = b;
b = c;
c = nextTerm;
}
}
But this has to be used carefully, because Methods like Min() will go crazy with this. But you can use e.g. InfiniteTribonacciSequence.Take(5).Last() to get the 5th element of the sequence.
I think the recursive way is too suitable for such cases:
example:
using System.IO;
using System;
class Program
{
static void Main()
{
int a=4, b;
b=tribo(a);
Console.WriteLine(b);
}
static public int tribo(int n)
{
if(n==0) return 0;
if(n==1) return 1;
if(n==2) return 1;
return(tribo(n-1)+tribo(n-2)+tribo(n-3));
}
}
this gives the series 0 1 1 2 4 7 13 24 ...

Categories