Is there any better way to do this in C++? Check which numbers satisfy the condition [A*B*C = A! + B! + C!] - c++

This is what I came up with
#include <iostream>
using namespace std;
int serialNumber = 1;
Would recursion be better?
int factorial(int n)
{
int k=1;
for(int i=1;i<=n;++i)
{
k=k*i;
}
return k;
}
How can I go about doing this in a single for loop?
Or is this the best way?
int main()
{
int a;
int b;
int c;
int fact1;
int fact2;
int fact3;
for (a=1;a < 11;a++)
{
fact1 = factorial(a);
for (b=1;b < 11;b++)
{
fact2 = factorial(b);
for (c=1;c < 11;c++)
{
fact3 = factorial(c);
cout << serialNumber << " : ";
int LHS = fact1 + fact2 + fact3;
if (LHS == a * b * c)
{
cout << "Pass:" <<" "<< a << " & " << b << " & " << c << endl;
}
else
{
cout << "Fail" <<endl;
}
serialNumber++;
}
c = 1;
}
b = 1;
}
return 0;
}
I am being forced to add more none code into it.
Thanks for the help!

Don't know if this is helps,but>
check for minimum of A,B,C
A!+B!+C! = (min(A,B,C)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))
So, you can calculate the minimum factorial and than re-use it for calculating others.
On the other hand, you can calculate only the maximum factorial and store its results in the array, and re-use pre-calculated values for finding factorial of smaller numbers
Other implication is that the minimum number can be reduced
restfact1 * restfact2 = ((min-1)!)*(1+((min+1..restfact1)!)+((min+1..restfact2)!))

Part of the question was how can this be done in a single loop and this is one way to do that.
I don't think this is a better way of doing it, but the question was asked:
constexpr int bound = 10;
int Factorials[bound + 1];
for (int i = 1; i <= bound; ++i) Factorials[i] = Factorial(i);
for (int i = 0; i < bound * bound * bound; ++i) {
int s = i + 1;
int a = i;
int c = 1 + a % bound;
a /= bound;
int b = 1 + a % bound;
a /= bound;
++a;
cout << s << " : ";
int LHS = Factorials[a] + Factorials[b] + Factorials[c];
if (LHS == a * b * c)
...
}

Related

Can anyone explain what is the error I am getting in the output and how to remove it?

My code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int BinaryToDecimal(int n)
{
int ans = 0;
int x = 1;
while (n > 0)
{
int y = n % 10;
ans = ans + x * y;
x = x * 2;
n = n / 10;
}
return ans;
}
int DecimalToBinary(int num)
{
vector<int> vect;
while (num > 0)
{
vect.push_back(num % 2);
num = num / 2;
}
int s = vect.size();
int i = s - 1;
for (i = s - 1; i >= 0; i--)
{
cout << vect.at(i);
}
return vect.at(i);
}
int main()
{
int a, b;
cout << "Enter first number: " << endl;
cin >> a;
cout << "Enter second number: " << endl;
cin >> b;
int a_deci = BinaryToDecimal(a);
int b_deci = BinaryToDecimal(b);
int sum = a_deci + b_deci;
DecimalToBinary(sum);
cout << endl;
return 0;
}
Output:
Enter first number:
10101
Enter second number:
11010
101111terminate called after throwing an instance of 'std::out_of_range'what(): vector::_M_range_check: __n (which is 18446744073709551615) >= this->size() (which is 6)
What does this error message mean and how do I fix it?
After this for loop
for (i = s - 1; i >= 0; i--)
{
cout << vect.at(i);
}
the variable i is equal to -1.
So the next call of the member function at with the value equal to -1 (that yields a very big number of the unsigned type std::vector<int>::size_type)
return vect.at(i);
throws the exception.
It seems you need to return from the function the whole vector elements of which will represent a number in the binary form.
Instead of the container std::vector<int> it will be better to use std::bitset.

Windows C++ char not displaying properly, just some unknkown character displaying

I have written the code for RSA in C++ on Ubuntu. It was working fine on that, it's working fine on Windows Dev C++ as well, but it doesn't show the character properly.
Here is the code :
#include<iostream>
#include<stdlib.h> // for rand()
#include<math.h> // for floor function
#include<string.h>
using namespace std;
//function to check whether a number is prime or not
int check_prime(int number)
{
int count = 0;
for(int i = 2; i<number + 1; i++)
{
if(number%i == 0)
{
count++;
}
}
if(count>2)
{
return 0;
}
else
{
return 1;
}
}
//function to generate a random prime number
int generate_random_prime()
{
int temp;
while(1)
{
temp = rand() % 50;
if(check_prime(temp) == 1)
{
return temp;
}
}
}
int gcd(int a, int b)
{
int temp;
while(b != 0)
{
temp = b;
b = a%b;
a = temp;
}
return a;
}
// Extended Euclid GCD to find d such de congruent to 1
int extended_gcd(int a, int b)
{
int d, x, y, r, q;
if(b == 0)
{
d = a;
x = 1;
y = 0;
cout << "\n d= " << d << " x= " << x << " y= " << y << "\n";
}
int x2, x1, y2, y1;
x2 = 1;
x1 = 0;
y2 = 0;
y1 = 1;
while(b > 0)
{
q = floor(a / b);
r = a - q*b;
x = x2 - q*x1;
y = y2 - q*y1;
a = b;
b = r;
x2 = x1;
x1 = x;
y2 = y1;
y1 = y;
}
d = a;
x = x2;
y = y2;
return x2;
}
//returns a^b mod n using square and multiply method
int modular_exponentiation(int a, int b, int n)
{
if(a == 1)
{
return 0;
}
int c = 1;
for(int i = 1; i < b + 1; i++)
{
c = (c*a) % n;
}
return c;
}
//cipher text = (message^e) %n
int cipher_text(int m, int e, int n)
{
return modular_exponentiation(m, e, n);
}
//decrypted_text= (cipher^d)%n
int decrypt_cipher(int c, int d, int n)
{
return modular_exponentiation(c, d, n);
}
int main()
{
// generating two random prime p and q
int p = generate_random_prime();
int q = generate_random_prime();
cout << "Prime p : " << p << "and q : " << q << "\n";
int n = p*q;
cout << "n=p*q = " << n << "\n";
//calculating Euler Totient for prime p and q
int euler_phi = (p - 1)*(q - 1);
cout << "Euler totient is : " << euler_phi << "\n";
int d, e;
// calculating e such that 1<e<euler_phi and gcd(n,euler_phi)=1
while(1)
{
e = rand() % (euler_phi - 1 + 1) + 1;
if(gcd(euler_phi, e) == 1)
{
break;
}
}
cout << "e value is : " << e << "\n";
//calculating d such that ed congruent 1, ed=1
d = extended_gcd(e, euler_phi);
//d=5;
cout << "d value is : " << d << "\n";
//storing the message to be encrypted as char array and encrypting each char element
char message[20];
int cipher[20];
cout << "Enter the message to be encrypted : ";
cin >> message;
cout << "Message to be encrypted is : " << message << "\n";
int size = strlen(message);
//calculating cipher text c
for(int i = 0; i < size; i++)
{
cipher[i] = cipher_text(int(message[i]), e, n);
}
cout << "Cipher text is : ";
for(int i = 0; i < size; i++)
{
cout << cipher[i] << " ";
}
char message_decrypted[size];
//decrypting cipher text
for(int i = 0; i < size; i++)
{
message_decrypted[i] = decrypt_cipher(cipher[i], d, n);
}
cout << "\nDecrypted message is : ";
for(int i = 0; i < size; i++)
{
cout << message_decrypted[i];
}
cout << "\n";
return 0;
}
I have tried the code on DevC++ and using g++.
Check the images :
Image using g++ compiler
I need a way to print the char to be displayed properly.
I think that message_decrypted[i]=decrypt_cipher(cipher[i],d,n); needs to be changed to print the character properly in Devcpp
Here is the link to the code in online IDE where it works fine https://repl.it/#shubhamjohar/RSA
When your main routine invokes
decrypt_cipher(cipher[i], d, n);
cipher[0] is 386 as matching your output above. d is -179. And n is 697
The corresponding call into modular_exponentiation(a=386, b=-179, n=697) results in this for-loop getting skipped:
for (int i = 1; i<b + 1; i++) {
c = (c*a) % n;
}
Because i < (b + 1) evaluates to (1 < -178), which evaluates to false.
Therefore, your modular_exponentiation returns 1, which is an unprintable character.
Same applies for the subsequent calls to decrypt_cipher from main.
I don't know enough about the RSA algorithm to know if your implementation is correct. But when d is negative, that for-loop isn't going to do any loops.
Maybe it is incurred by the following expression in your program:
char message_decrypted[size];
There is some standard change related to this usage. please read the following page for more details.
https://www.geeksforgeeks.org/variable-length-arrays-in-c-and-c/
Or try to use something like new char[size] to allocate memory dynamically.

C++ : Recursion (Variables losing value)

I made a simple recursion program for this question http://www.spoj.com/problems/COINS/, but whenever recursion happens my class variables lose their value and store the value from the recursion loop.
Here's the code:
#include<iostream>
using namespace std;
class a
{
public:
int c = 0, d = 0, b = 0, x = 0;
int recur(int n)
{
b = (n / 2);
if (b >= 12)
{
b = recur(b);
}
c = (n / 3);
if (c >= 12)
{
c = recur(c);
}
d = (n / 4);
if (d >= 12)
{
d = recur(d);
}
x = b + c + d;
return x;
}
};
int main()
{
int n;
while(cin)
{
cin >> n;
int b = 0, r = 0;
a abc;
r = (n > abc.recur(n)) ? (n) : (abc.recur(n));
cout << r << endl;
}
return 0;
}
So for input 12, I'll be getting 13 but for the input value of 44 I'm getting 44.
This could be a working solution:
#include <iostream>
using namespace std;
int changeToDollars(int bytelandians) {
int byTwo = bytelandians / 2;
int byThree = bytelandians / 3;
int byFour = bytelandians / 4;
int sum = byTwo + byThree + byFour;
if (sum < bytelandians) {
return bytelandians;
} else {
return changeToDollars(byTwo) + changeToDollars(byThree) + changeToDollars(byFour);
}
}
int main() {
int bytelandians;
cout << "How much bytelandians?: ";
while (cin >> bytelandians) {
cout << "Corresponding $: " << changeToDollars(bytelandians) << endl;
cout << "How much bytelandians?: ";
}
return 0;
}
The changeToDollars function, using a simple recursive algorithm, exchanges each single Byteland coin into the corresponding three ones with minor value, until the overall converted amount is advantageous.

C++: implementing Modular Exponentiation

I am using this New and improved code I corrected in order to solve this question I have.
I am using modular Exponentiation to use the formula [a^k mod n] to get my answer for an assignment I had to do where I was required to code it in two steps.
First int k must be converted to a binary
representation K consisting of a list of 0s and 1s. Second, Modular Exponentiation must be performed
using a, n and K[] as arguments..
Earlier My code was incorrect and was able to correct it.
The Problem I now face is that when I google the online calculator for modular Exponentiation of 5^3 % 13, it should == 8
The result that I get from my code is 5.
I am trying to understand if there something minor I'm missing from the code or my math is wrong? Thanks
#include <iostream>
#include <vector>
using namespace std;
vector <int> BinaryK(int k);
int ModularExpo(int a, vector <int> & k, int n);
int main()
{
int a = 0;
int k = 0;
int n = 0;
cout << "a^k % n" << endl;
cout << "a = ";
cin >> a;
cout << "k = ";
cin >> k;
cout << "n = ";
cin >> n;
vector<int> B = BinaryK(k);
int result = ModularExpo(a, B, n);
cout << "a ^ k mod n == " << result << endl;
return 0;
}
// c == b^e % m
vector<int> BinaryK(int k)
{
vector<int> K; //hint: make K a vector
int tmp = k;
while (tmp > 0)
{
K.push_back(tmp % 2); //hint: use pushback
tmp = tmp / 2;
}
return K;
}
int ModularExpo(int a, vector<int> & K, int n)
{
if (n == 1)
return 0;
int b = 1;
if (K.size() == 0)
return b;
int A = a;
if (K[0] == 1)
b = a;
for (int i = 1; i < K.size() - 1; i++)
{
A = A * A % n;
if (K[i] == 1)
b = A*b % n;
}
return (b);
}
Change this one line:
for (int i = 1; i < K.size(); i++) // K.size() not K.size()-1

C++, Math exponents

I have this problem in making a program that helps me with this.
For n (n <= 25). Make a program that calculates and shows on the screen the value of the sum:
S= 1+ 2+ 2(pow 2)+ 2(pow 3)+...+2(pow n).
what i managed to do is this :
#include <iostream>
#include <math.h>
using namespace std;
int i;
int n;
long s;
long f() {
if (n=0) {
return 1;
}else if (n=1) {
return 2;
}else {
return 2* (n-1);
}
}
int main() {
for (i=0; n<=2;++n){
s=s+f();
cout << s <<endl;
}
}
The main code is wrong i know that for sure but i do not know how to do it..please help me, im just a c++ begginer and trying to learn the language on my own.
The specific things you're doing wrong...
int i;
int n;
long s;
Don't use globals like this. You should need no globals at all for this program.
long f() {
if (n=0) {
return 1;
}else if (n=1) {
return 2;
}else {
return 2* (n-1);
}
}
Here you're using recursion where you should use a loop instead. Also, n should be a passed-in parameter:
long f(int n) {
long result = 1;
for(int i = 0; i < n; ++i)
result *= 2;
return result;
}
Or even better, don't reinvent the wheel and use pow(2, n) instead of f(n).
for (i=0; n<=2;++n){
You set i but never do anything with it.
You never initialize n or s so they could have random values (though these days compilers are nicer to people and set all the uninitialized globals to 0, but you really shouldn't depend on that).
Ergo, you should have written n=0 instead of i=0.
How it could have looked if you didn't use globals:
int main() {
long s = 0;
for (int n = 0; n <= 2; ++n){
s += f(n);
cout << s <<endl;
}
}
This is just a geometric series. Sum of n terms of geometric series is given by:-
S(n) = a ( r^n - 1 )/ (r - 1 )
n = no. of terms.
r = common ratio.
a = first term.
So, for your example...
a = 1.
r = 2.
n = no of terms you want to take sum.
2(pow n) may be written 1 << n
or if you want to compute yourself the power of two:
// compute manually (1 << n)
int power2(int n)
{
int res = 1;
for (int i = 0; i != n; ++i) {
res *= 2
}
return res;
}
Your sum is in fact power2(n+1) - 1, so you may simply write:
std::cout << ((1 << n + 1) - 1) << std::endl;
or
std::cout << power2(n + 1) - 1 << std::endl;
if you want to do that in loop:
unsigned int res = 0;
for (int i = 0; i != n; ++i) {
res += power2(i);
}
std::cout << res << std::endl;
All you need is a variable to hold the current sum and another variable to hold the power of 2:
int main()
{
const int n = 25;
int pow2 = 1;
int sum = 1;
for (int i = 1; i <= n; i++)
{
pow2 *= 2;
sum += pow2;
}
cout << sum << endl;
}