Generating public key from private key issues - c++

I am using the BigIntegerLibrary and this is applying secp256k1.
Here is my function to generate the public key.
std::string genPublicKey(BigInteger privateKey){
std::vector<bool> sequence = reducePointOps(privateKey);
BigInteger s;
BigInteger x3 = basePoint_X;
BigInteger y3 = basePoint_Y;
BigInteger rx, ry;
BigInteger three(3);
BigInteger two(2);
for(std::vector<bool>::reverse_iterator it = sequence.rbegin(); it != sequence.rend(); ++it){
//meaning point doubling
if(*it == true){
s = (((three * ((x3 * x3)%primeModulo))+a) * inverse(two*y3)) % primeModule;
rx = (((s*s)%primeModulo)-(two * x3))% primeModulo;
ry = (s * (x3 - rx) - y3)%primeModulo;
//cout<<"Doubling: s="<<s<<", x="<<rx<<", y="<<ry<<endl;
}
//meaning point addition
else{
//(x2,y2) -> base point (x1,y1)->(x3, y3) aka previously calculated point
s = ((basePoint_Y - y3) * inverse(basePoint_X - x3))%primeModulo;
rx = (((s*s) % primeModulo) - x3 - basePoint_X) % primeModulo;
ry = ((s * (x3 - rx)) - y3)%primeModulo;
//cout<<"Addition: s="<<s<<", x="<<rx<<", y="<<ry<<endl;
}
//cout<<endl;
x3=rx;
y3=ry;
}
std::string x3_str = bigIntegerToString(x3);
std::string y3_str = bigIntegerToString(y3);
return (x3_str + y3_str);
}
Here is my inverse function but I took this from somewhere so I am almost positive it is correct. Plus I have tested it and is working.
BigInteger inverse(BigInteger a){
BigInteger s;
BigInteger t;
eea(primeModulo, a, &s, &t);
if(t<0)
return (t%primeModulo);
else
return t;
}
BigInteger eea(BigInteger a, BigInteger b, BigInteger *s, BigInteger *t){
if(a==0){
*s=0;
*t=1;
return b;
}
BigInteger s1;
BigInteger t1;
BigInteger gcd = eea(b%a, a, &s1, &t1);
*s = t1 - (b/a) * s1;
*t = s1;
return gcd;
}
Other than that there is only my function to reduce the amount of operations to point doublings and additions. I have worked out many examples by hand so I know the data coming out of this function is correct.
The weird thing is that I have tried this on an example in my cryptography class with values m=17 x=5 y=1 a=2 and I am getting all the values I should be getting. I didn't code a way for the values to 'wrap around' once the inverse of the base point is reached but since with bitcoin the private key space is much much smaller than the modulo value so we shouldn't even reach that point when values start repeating themselves. I am about to cry with how frustrating this is so any help would be wonderful.
Oh also there is one other weird thing. Here is an example when I run it.
Private Key:
18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725
My Public Key:
458ACBDD5DE95281B9ACAB95D0F8DAC011C895EBE95E567BE9E308C12936CCAE3B81CE567B126A604A938D29ED15B5A96779AF27B5DC9ED6F2EE187E9C582BA6
Correct Public Key:
50863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B23522CD470243453A299FA9E77237716103ABC11A1DF38855ED6F2EE187E9C582BA6
It's not obvious but the last 19 hex digits are the same but the rest is different? They are the same length by the way. Could this be something wrong with the BigInteger Library? This was a way that seemed simple to me but would you recommend I did it a different way?

Related

C++ Karatsuba long integer algorithm error

i got this error = Unhandled exception at 0x7A5B1088 (ucrtbased.dll) in algorthmprokect1.exe: 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x006B2FF4). occurred
i don't know where i have a mistake i am using strings because i need to get integers from file and they has 1000 digits
Update:After Debugging i realized that else statement runs infinite number of times but i still didn't found the solution.
string karatsuba(string X,string Y) {
if (X.length()==1 || (X.length()==2 && ((X.substr(0, 1).compare("-") == 0))))
{
int buf = stoi(X) * stoi(Y); //multiply if int has single digit
return to_string (buf);
}
else
{
string X1 = X.substr(0, (X.length()/2)); //divide half to X
string X2 = X.substr((X.length() / 2), X.length());
string Y1 = Y.substr(0, (Y.length() / 2)); // divide half to Y
string Y2 = Y.substr((Y.length() / 2) , Y.length() );
string U= karatsuba(X1, X2);
string V = karatsuba(Y1, Y2);
string W = karatsuba(to_string(stoi(X1) - stoi(X2)), to_string(stoi(Y1) - stoi(Y2)));
string Z = to_string(stoi(U) + stoi(V) - stoi(W));
string P = to_string(pow(10, X.length()) * stoi(U) + pow(10, X.length() / 2) * stoi(Z) + stoi(V));
return P;
}
}
This code is not working properly because of the infinite recursion.
But this is not the main problem of it.
The main problem is: it's a brilliant example of how not to do. You are severe underqualified to do such tasks. There is no point in attempts to fix this code, you must simply put it into trash. I would recommend to start with the GNU MP library. You can learn much from the source code and documentation there how to work with big integers and implement big integer algorithms. You may also try to read this source.

Efficiently preventing duplicate accesses

I have a statement computing a multiply-accumulate operation that looks something like this:
return A->set(A->get() + B->get() * C->get());
Now, A, B, and C may not be unique, and I want to minimize redundant get()s. The only way I can think of optimizing this is with
if (A == B && B == C) {
double a = A->get();
return A->set(a + a * a);
} else if (A == B) {
double a = A->get();
return A->set(a + a * C->get());
} else if (A == C) {
double a = A->get();
return A->set(a + B->get() * a);
} else if (B == C) {
double b = B->get();
return A->set(A->get() + b * b);
} else {
return A->set(A->get() + B->get() * C->get());
}
Is there a more efficient way? What about generalizing this to more than three arguments??
You can store them in a map. The solution can be extended easily to arbitrarily many pointers, but I've used three here for concreteness.
std::unordered_map<MyType *, double> computed_values;
for (MyType *p: {A, B, C}) {
if (computed_values.find(p) == computed_values.end()) {
computed_values[p] = p->get();
}
}
double result = computed_values[A] + computed_values[B] * computed_values[C];
A->set(result);
As others have pointed out, make sure you profile to make sure this is actually worth the overhead of std::unordered_map lookups.
Assuming get() methods are really costly to the extent of producing measurable performance difference,
double a,b,c;
a = A->get();
b = (B==A?a:B->get());
c = (C==B?b:(C==A?a:c->get()));
return A->set(a+b*c);
Assuming the get() methods are reasonably cheap, you'd be better off just doing:
return A->set(A->get() + B->get() * C->get());
The other approach simply inserts a bunch of conditional jumps into your code, which could easily end up being more expensive than the original code.

use typedef for more type safe in c++

I would like to revisit the post. Currently, I am trying to avoid bug created by mixing Rad and Degree types for angles in my program.
For example:
typedef float Degree;
typedef float Radian;
Degree a = 15.;
Radian b = 3.14/4.;
float c = a + b; // no compile error
is there new update solution for this?
EDIT 01:
I resort to write my own class with hope for its small size and no dependency. Here's the working code
#include <stdio.h>
#include <iostream>
template<typename numT>
class RadAngle {
public:
RadAngle() {
AngVal = 0.0;
}
RadAngle(const numT& angV) {
AngVal = angV;
}
void operator = (const RadAngle<numT>& ang1) {
AngVal = ang1.getVal();
}
RadAngle operator+(const RadAngle<numT>& ang1) const { return RadAngle<numT>(AngVal+ang1.getVal()); }
RadAngle operator-(const RadAngle<numT>& ang1) const { return RadAngle<numT>(AngVal-ang1.getVal()); }
RadAngle operator*(const RadAngle<numT>& ang1) const { return RadAngle<numT>(AngVal*ang1.getVal()); }
RadAngle operator/(const RadAngle<numT>& ang1) const { return RadAngle<numT>(AngVal/ang1.getVal()); }
numT getVal() const { return AngVal;};
private:
numT AngVal;
};
int main() {
RadAngle<float> a(1.5);
RadAngle<float> b(3.14);
RadAngle<float> c = a+b;
//std::cout << c << std::endl;
// printf("%.2f",c.getVal());
return 0;
}
What you have doesn't help type safety at all, except perhaps as weak documentation. As far as the compiler is concerned, float, Degree, and Radian are complete synonyms; this is called a weak type alias. Strong type aliases are not a part of C++, but you can work around that. Two good articles on that are here and here. The basic idea is to create a generic class template for a strong typedef, and use that to create each individual alias.
If you don't want to write all the boilerplate yourself even once, I recommend using a third-party library to handle this. Both the authors of the posts I linked above wrote libraries for it, NamedType and type_safe. If you need something heavier-duty, you should check out Boost.Units. Note that I haven't used any of these myself; they're just where I'd check if I needed those features.
You didn't ask about this, but none of this should have any runtime performance costs over just using float everywhere and keeping track of units manually, but might make compilation slower.
Your best bet is to create a class for each kind of measurement and implement ways to convert one to another. The classes could/should have a common superclass.
I would pick one as internal representation (e.g. Radian) and write other as wrapper classes
typedef double Radian;
class Degree {
public:
Degree() {
m_radian = 0.0;
}
Degree(double degree) {
m_radian = degree / 180.0 * 3.1415926;
}
void operator = (double degree) {
m_radian = degree / 180.0 * 3.1415926;
}
operator Radian() const { return m_radian; }
private:
Radian m_radian;
};
void print_rad(Radian rad) {
printf("rad: %lf\n", rad);
}
int main() {
Radian rad = 123.0;
Degree degree = 456.0;
print_rad(rad);
print_rad(degree);
print_rad(rad + degree);
return 0;
}
Output:
rad: 123.000000
rad: 7.958701
rad: 130.958701
Well, you probably want to go the whole way with calculating with units.
Do something like this, with all relevant (SI?) base-units:
template <class T, int meter, int second, int pow_10, int pow_deginrad>
class unit {
T num = 0;
};
// add convenience typedefs. Also look into `operator ""` for denoting literals.
Now you only have to define arithmetic between the types and magnitudes in one place.
Happy coding.
Your approach is a bit flawed, I think.
What you trying to model are physical quantities - types that have a value and a unit.
There is no quantity called a radian. There is a quantity called angle whose units may be radians or degrees.
What you need to is a bit of infrastructure to deal with converting units of quantities and performing operations on units as well as the values.
For example,
L1 = 10 "m" (length)
L2 = 20 "m" (length)
L1 * L2 = 200 "m^2" (area)
F1 = 10 "N" (force)
A1 = 2 "m^2" (area)
F1/A1 = 5 "Pa" (pressure)
A2 = 10 "deg"
convert(A2, "rad") = 0.174533 "rad"
If you are able to add the code for dealing with units, rest of the functionality will be easy.
We have had to do that at my work and the amount of code is non-trivial. It does not make sense for me delver further into that subject here.
Potential C++ code:
struct Quantity
{
double value;
std::string unit;
};
// Defines operations on Quantity.
Quantity operator+(Quantity const& q1, Quantity const& q2) { ... }
Quantity operator-(Quantity const& q1, Quantity const& q2) { ... }
Quantity operator*(Quantity const& q1, Quantity const& q2) { ... }
Quantity operator*(Quantity const& q1, double f) { ... }
Quantity operator/(Quantity const& q1, Quantity const& q2) { ... }
Quantity operator/(Quantity const& q1, double f) { ... }
Quantity convert(Quantity const& q, std::string const& unit) { ... }
auto L1 = Quantity(10, "m");
auto L2 = Quantity(10, "m");
auto a = L1*L2; // Resulting in Quantity(100, "m^2")
auto F1 = Quantity(10, "N");
auto A1 = Quantity(2, "m^2");
auto p = F1/A1; // Resulting in Quantity(5, "Pa")
auto A2 = Quantity(10, "deg");
auto A3 = Convert(A2, "rad"); // Resulting in Quantity(0.174533, "rad")

Object-oriented API for equations

Let's take the Quadratic equation as an example:
a x^2 + b x + c = 0
This equation can be viewed as describing a relation between the values a, b, c, and x. Given three of those, you can calculate the fourth. The four possibilities are:
a = - (b x + c) / x^2
b = - (a x^2 + c) / x
c = - x (a x + b)
x = [-b +- sqrt(b^2 - 4 a c)] / (2 a)
Here's one approach to representing this equation. Given the following class:
class Quadratic
{
public:
double a; bool HasA = false; void A(double a_) { a = a_; HasA = true; }
double b; bool HasB = false; void B(double b_) { b = b_; HasB = true; }
double c; bool HasC = false; void C(double c_) { c = c_; HasC = true; }
double x; bool HasX = false; void X(double x_) { x = x_; HasX = true; }
// a = - (b x + c) / x^2
double A()
{
if (HasB == false) throw domain_error("B not set");
if (HasC == false) throw domain_error("C not set");
if (HasX == false) throw domain_error("X not set");
if (x == 0.0) throw domain_error("X cannot be 0.0");
return - (b*x + c) / (x*x);
}
// x = [-b +- sqrt(b^2 - 4 a c)] / (2 a)
vector<double> X()
{
if (HasA == false) throw domain_error("A not set");
if (HasB == false) throw domain_error("B not set");
if (HasC == false) throw domain_error("C not set");
if (a == 0.0) throw domain_error("A cannot be 0.0");
return
{
(-b + sqrt(b*b - 4 * a*c)) / (2 * a),
(-b - sqrt(b*b - 4 * a*c)) / (2 * a)
};
}
// b = - (a x^2 + c) / x
// ...
// c = - x (a x + b)
// ...
};
We can find x as follows. Set A, B, and C:
obj.A(2.3);
obj.B(3.4);
obj.C(1.2);
There might be two values for X so iterate through the result:
for each (auto elt in obj.X()) cout << elt << endl;
If any of the dependent values are not set, a domain_error exception is thrown.
Similarly, to find A, we set B, C, and X:
obj.B(1.2);
obj.C(2.3);
obj.X(3.4);
and display the result:
cout << obj.A() << endl;
My question is, are there other approaches to representing and working with equations in an object-oriented language? Is there a more idiomatic approach than the above?
The title of your question says:
Object-oriented API for equations
However, there is nothing object-oriented about your code example, at least not with the established definitions of "object-oriented programming" I know. You have no virtual functions, so it's not object-oriented.
Bjarne Stroustrup's FAQ "What is "OOP" and what's so great about it?" says (emphasis added by me):
In the context of C++ [...] it means programming using class hierarchies and virtual
functions to allow manipulation of objects of a variety of types
through well-defined interfaces and to allow a program to be extended
incrementally through derivation.
The Standard C++ FAQ (which also quotes from the first source), answers "Are virtual functions (dynamic binding) central to OO/C++?" like this:
Without virtual functions, C++ wouldn’t be object-oriented.
Therefore,
My question is, are there other approaches to representing and working
with equations in an object-oriented language?
The answer to that should be that mathematical computations and object-orientation programming usually do not mix well. Object orientation is all about choosing the concrete implementation of an abstract operation at run-time. You may, for example, choose a different algorithm with the same input and output based on the user's choice at run-time. This could be done with virtual functions. Still, the object-orientation would happen at a higher level of your application, and the computation itself would not be object-oriented.
Is there a more idiomatic approach than the above?
Yes, generic programming, i.e. templates.
All the code you presented works with double values. What if I want to use it with float, std::complex<double> or a even a custom BigNumber class?
With templates, you can write generic code with concrete implementations chosen at compile-time.
First of all, let's make your original code compilable:
#include <vector>
#include <stdexcept>
#include <math.h>
class Equation
{
public:
bool HasA;
bool HasB;
bool HasC;
bool HasX;
double a;
double b;
double c;
double x;
double A()
{
if (!HasB) throw std::domain_error("B not set");
if (!HasC) throw std::domain_error("C not set");
if (!HasX) throw std::domain_error("X not set");
if (x == 0.0) throw std::domain_error("X cannot be 0.0");
return - (b*x + c) / (x*x);
}
// x = [-b +- sqrt(b^2 - 4 a c)] / (2 a)
std::vector<double> X()
{
if (!HasA) throw std::domain_error("A not set");
if (!HasB) throw std::domain_error("B not set");
if (!HasC) throw std::domain_error("C not set");
if (a == 0.0) throw std::domain_error("A cannot be 0.0");
return
{
(-b + sqrt(b*b - 4 * a*c)) / (2 * a),
(-b - sqrt(b*b - 4 * a*c)) / (2 * a)
};
}
// b = - (a x^2 + c) / x
// ...
// c = - x (a x + b)
// ...
};
int main()
{
Equation e;
std::vector<double> v = e.X();
}
(I've fixed the == false comparisons, which are almost always bad style, but there is more work to do from a C++ coding quality POV, e.g. making the member variables private.)
The problem is that this whole thing only works for doubles. If you try to use it with ints, here's what happens:
int main()
{
Equation e;
std::vector<int> v = e.X();
}
Result:
error C2440: 'initializing' : cannot convert from
'std::vector<double,std::allocator<_Ty>>' to 'std::vector<int,std::allocator<_Ty>>'
Here's how you can turn your class into a template: add template <class T> on top and replace every double with T (and add two static_casts to tell the compiler that you agree with a narrowing conversion which may happen due to sqrt's return type):
#include <vector>
#include <stdexcept>
#include <math.h>
template <class T>
class Equation
{
public:
bool HasA;
bool HasB;
bool HasC;
bool HasX;
T a;
T b;
T c;
T x;
T A()
{
if (!HasB) throw std::domain_error("B not set");
if (!HasC) throw std::domain_error("C not set");
if (!HasX) throw std::domain_error("X not set");
if (x == 0.0) throw std::domain_error("X cannot be 0.0");
return - (b*x + c) / (x*x);
}
// x = [-b +- sqrt(b^2 - 4 a c)] / (2 a)
std::vector<T> X()
{
if (!HasA) throw std::domain_error("A not set");
if (!HasB) throw std::domain_error("B not set");
if (!HasC) throw std::domain_error("C not set");
if (a == 0.0) throw std::domain_error("A cannot be 0.0");
return
{
static_cast<T>((-b + sqrt(b*b - 4 * a*c)) / (2 * a)),
static_cast<T>((-b - sqrt(b*b - 4 * a*c)) / (2 * a))
};
}
// b = - (a x^2 + c) / x
// ...
// c = - x (a x + b)
// ...
};
int main()
{
Equation<int> e;
std::vector<int> v = e.X();
}
Of course, this is only half of the story, because chances are very high that you do not want to allow integral types anyway, only floating-point types like double or float (or custom floating-point types). The result of sqrt(2) truncated to 1 is rarely desirable.
To keep your code generic but prevent such problems, read up on static assertions for compile-time checks, restricting your template to particular types. std::is_floating_point may be useful, too. See also the following recent question on SO:
Getting std::complex<double> to pass std::is_floating_point test
And remember, nothing of this has anything to do with object-oriented programming.

number of possible ways of assigning free plots to buildings with the restriction that no two consecutive plots exist on which it is allowed to build

I can't seem to find a solution for this anywhere. Given below is a description of the problem:
Problem Statement
King Kohima has reserved a new exclusive street for his executive class employees where they can build their homes .He has assigned you to plan that street .You have to decide on which plots along the street it is allowed to build new buildings. In order to this, you want to calculate first the number of possible ways of assigning free plots to buildings with the restriction that no two consecutive plots exist on which it is allowed to build - you want to give the inhabitants the feeling that they have more free room so that they can live happily. The street is divided into M sections. Each section corresponds to two plots, one on each side of the street. Find the number of possible assignments.
Input/Output Specs
Input Specs
In the first line you're given M ( 0 < M ≤ 1000 ).
Output Specs
You need to output result to variable output1.
Note: In case there is no possible solution, you need to return 0 as output.
Example
Input:
3
Output:
25
Example explanation:
If we just look at the one street side and mark X as a plot where building is allowed and Y as a free plot, we have: XYX, YXY, YYX, XYY, YYY.
Since the same number exists on the other side, we have 5*5 = 25 combinations.
This question can be solved by Dynamic programming. If we store the count of number of X and number of Y, If the end Character is Y then it results in two strings, by appending X and Y at the end, But if the last character is X, then only one string can be generated by appending Y at the end. This gives the answer
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class KingKohima {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int M=Integer.parseInt(br.readLine());
long countX[]=new long[M+1];
long countY[]=new long[M+1];
countX[0]=0; countY[0]=0;
countX[1]=1; countY[1]=1;
countX[2]=1; countY[2]=2;
for(int i=3;i<=M;i++){
countX[i]=countY[i-1];
countY[i]=countX[i-1]+countY[i-1];
}
long finalCount=countX[M]+countY[M];
System.out.println(finalCount*finalCount);
}
}
This problem is related to Permutations and Combinations especially binomial theorem. Scope is those who good in that, they can get mathemical equation for this problem and then, its easy for any M as input in that equation.
But with coding, python solution can be:
from itertools import product
M = 7 #change as per need
cnt = 0
l = []
for w in product(['x','y'], repeat=M):
tmp = ''.join(w)
if 'xx' not in tmp:
l.append(tmp)
cnt += 1
print cnt*cnt
print l
output instance:
1156
['xyxyxyx', 'xyxyxyy', 'xyxyyxy', 'xyxyyyx', 'xyxyyyy', 'xyyxyxy', 'xyyxyyx', 'xyyxyyy', 'xyyyxyx', 'xyyyxyy', 'xyyyyxy', 'xyyyyyx', 'xyyyyyy', 'yxyxyxy', 'yxyxyyx', 'yxyxyyy', 'yxyyxyx', 'yxyyxyy', 'yxyyyxy', 'yxyyyyx', 'yxyyyyy', 'yyxyxyx', 'yyxyxyy', 'yyxyyxy', 'yyxyyyx', 'yyxyyyy', 'yyyxyxy', 'yyyxyyx', 'yyyxyyy', 'yyyyxyx', 'yyyyxyy', 'yyyyyxy', 'yyyyyyx', 'yyyyyyy']
So, that solves the problem. If there can be unexpected output for large M, please post comment.
Use recursion. I am not sure about the time complexity, because for large input it is taking hell lot of time(actually hangs up for large values). For small inputs i.e M < 10, this seems to give answers.
#include <iostream>
using namespace std;
int recur(char c, int num, int N) {
if (num == N) {
return 1;
}
if (num < N) {
if (c == 'X') {
return recur('Y', num + 1, N);
} else {
return (recur('X', num + 1, N) + recur('Y', num + 1, N));
}
}
}
int main()
{
int N = 4;
//x is number of combinations when the first slot is used to build a house
int x = recur('X', 1, N);
//y is number of combinations when the first slot is left empty
int y = recur('Y', 1, N);
cout << "x = " << x << endl;
cout << "y = " << y << endl;
//Since same number exists on other side also
cout << "total = " << (x + y) * (x + y) << endl;
return 0;
}
i would suggest a logic behind this. considering X as 1 and Y as 0.
010 101 000 100 001 are the cases where no two 1's are adjacent and sum=5.
return result 5*5. So generate binary numbers of 3 bits and increase the count for each such number.
If we have multiple test cases, then use this solution:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.HashMap;
public class KohimaKing {
static HashMap<Integer,BigInteger> fibboTerm = new HashMap<Integer,BigInteger>();
public static void main(String[] args) throws Exception
{
fibboTerm.put(new Integer(0),new BigInteger("0"));
fibboTerm.put(new Integer(1),new BigInteger("2"));
fibboTerm.put(new Integer(2),new BigInteger("3"));
Integer i=new Integer(3);
for(;i<=1000;i++)
{
fibboTerm.put(i, fibboTerm.get(i-2).add(fibboTerm.get(i-1)));
}
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter sections");
int m = Integer.parseInt(br.readLine());
System.out.println(fibboTerm.get(m).multiply(fibboTerm.get(m)));
}
}
I think recursion would be the best solution to this problem.
My idea is to think about a tree which can be formed with depth M, At last count the number of leaf nodes in the tree.
That's just an idea, Actual recursion can be started by thinking whether the first place can take X or not. It can take both X & Y only if it's parent(previous plot) has taken Y. But if it's parent has taken X, it can only take Y.
With this idea i made a recursion like.
int count=0; //Maintain a global counter to count the leaves
void fun(bool xTaken, int M)
{
if(M==0)
{
count++; //We've reached the leaf
return;
}
if(xTaken==false)
{
//We can take X
fun(true,M-1);
//or we can take Y
fun(false,M-1);
}
else if(xTaken==true)
{
//We can only take Y
fun(false,M-1);
}
}
And our answer will be count*count.
Again we can optimize this recursion by taking care of duplicate recursions by using memoization
I think, this formula might give the answer to the problem
For M sections, Total number of possible combinations of X and Y are 2^M, but we have to deduct the cases where 1) Two X are together 2) Three X are together 3) Four X are together and so on...till M X's are together.
Count = 2^M - (1! + 2! + 3!.........M-1!)
Final Answer = Count*Count
I'm not sure if this is the most efficient solution, but here goes
For a given value m, the total number of required arrangements are:
r=1;sum=0;
while(m>=r)
{
sum+=mCr;
m--;
r++;
}
for example, if m=7
ans= 7C1 + 6C2 + 5C3 + 4C4 ;
package HackerRank;
import java.io.IOException;
import java.util.Scanner;
class Tester1KingKohm {
public static void plotmaker(int input) {
int i = 1;
int countx = 1;
int county = 1;
while (i <= input) {
if (i > 1) {
int tempx = countx;
countx = county;
county = tempx + county;
}
i++;
}
System.out.println(countx + " " + county);
int total = countx + county;
int bothsidetotal = total * total;
System.out.println(bothsidetotal);
}
public static void main(String[] args) throws NumberFormatException, IOException {
Scanner sc = new Scanner(System.in);
plotmaker(sc.nextInt());
}
}
Here is a simple solution. This can be practiced here.
int getWays(int N, int i, int built, vector<vector<int>> &dp){
if(i==N) return 1;
if(dp[i][built]!=-1) return dp[i][built];
if(built==0) return dp[i][built]=(getWays(N, i+1, 1, dp)%1000000007)+(getWays(N, i+1, 0, dp)%1000000007)%1000000007;
return dp[i][built]=getWays(N, i+1, 0, dp);
}
int TotalWays(int N)
{
vector<vector<int>> dp(N, vector<int>(2, -1));
long long int ans=getWays(N, 0, 0, dp);
return (ans%1000000007)*(ans%1000000007)%1000000007;
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.HashMap;
public class KingKohima
{
public static void main(String[] args) throws Exception
{
BigInteger a = new BigInteger("2");
BigInteger b = new BigInteger("3");
BigInteger result = new BigInteger("0");
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
int m = Integer.parseInt(br.readLine());
if(m<=0)
{
System.out.println("0");
}
else if(m==1)
{
System.out.println("2");
}
else if(m==2)
{
System.out.println("3");
}
else
{
Integer i=new Integer(3);
for(;i<=m;i++)
{
result = a.add(b);
a=new BigInteger(b.toString());
b=new BigInteger(result.toString());
}
}
System.out.println(result.multiply(result));
}
}