Below is my pseudo code.
function highest(i, j, k)
{
if(i > j && i > k)
{
return i;
}
else if (j > k)
{
return j;
}
else
{
return k;
}
}
I think that works, but is that the most efficient way in C++?
To find the greatest you need to look at exactly 3 ints, no more no less. You're looking at 6 with 3 compares. You should be able to do it in 3 and 2 compares.
int ret = max(i,j);
ret = max(ret, k);
return ret;
Pseudocode:
result = i
if j > result:
result = j
if k > result:
result = k
return result
How about
return i > j? (i > k? i: k): (j > k? j: k);
two comparisons, no use of transient temporary stack variables...
Your current method:
http://ideone.com/JZEqZTlj (0.40s)
Chris's solution:
int ret = max(i,j);
ret = max(ret, k);
return ret;
http://ideone.com/hlnl7QZX (0.39s)
Solution by Ignacio Vazquez-Abrams:
result = i;
if (j > result)
result = j;
if (k > result)
result = k;
return result;
http://ideone.com/JKbtkgXi (0.40s)
And Charles Bretana's:
return i > j? (i > k? i: k): (j > k? j: k);
http://ideone.com/kyl0SpUZ (0.40s)
Of those tests, all the solutions take within 3% the amount of time to execute as the others. The code you are trying to optimize is extremely short as it is. Even if you're able to squeeze 1 instruction out of it, it's not likely to make a huge difference across the entirety of your program (modern compilers might catch that small optimization). Spend your time elsewhere.
EDIT: Updated the tests, turns out it was still optimizing parts of it out before. Hopefully it's not anymore.
For a question like this, there is no substitute for knowing just what your optimizing compiler is doing and just what's available on the hardware. If the fundamental tool you have is binary comparison or binary max, two comparisons or max's are both necessary and sufficient.
I prefer Ignacio's solution:
result = i;
if (j > result)
result = j;
if (k > result)
result = k;
return result;
because on the common modern Intel hardware, the compiler will find it extremely easy to emit just two comparisons and two cmov instructions, which place a smaller load on the I-cache and less stress on the branch predictor than conditional branches. (Also, the code is clear and easy to read.) If you are using x86-64, the compiler will even keep everything in registers.
Note you are going to be hard pressed to embed this code into a program where your choice makes a difference...
I like to eliminate conditional jumps as an intellectual exercise. Whether this has any measurable effect on performance I have no idea though :)
#include <iostream>
#include <limits>
inline int max(int a, int b)
{
int difference = a - b;
int b_greater = difference >> std::numeric_limits<int>::digits;
return a - (difference & b_greater);
}
int max(int a, int b, int c)
{
return max(max(a, b), c);
}
int main()
{
std::cout << max(1, 2, 3) << std::endl;
std::cout << max(1, 3, 2) << std::endl;
std::cout << max(2, 1, 3) << std::endl;
std::cout << max(2, 3, 1) << std::endl;
std::cout << max(3, 1, 2) << std::endl;
std::cout << max(3, 2, 1) << std::endl;
}
This bit twiddling is just for fun, the cmov solution is probably a lot faster.
Not sure if this is the most efficient or not, but it might be, and it's definitely shorter:
int maximum = max( max(i, j), k);
There is a proposal to include this into the C++ library under N2485. The proposal is simple, so I've included the meaningful code below. Obviously, this assumes variadic templates
template < typename T >
const T & max ( const T & a )
{ return a ; }
template < typename T , typename ... Args >
const T & max( const T & a , const T & b , const Args &... args )
{ return max ( b > a ? b : a , args ...); }
The easiest way to find a maximum or minimum of 2 or more numbers in c++ is:-
int a = 3, b = 4, c = 5;
int maximum = max({a, b, c});
int a = 3, b = 4, c = 5;
int minimum = min({a, b, c});
You can give as many variables as you want.
Interestingly enough it is also incredibly efficient, at least as efficient as Ignacio Vazquez-Abrams'solution (https://godbolt.org/z/j1KM97):
mov eax, dword ptr [rsp + 8]
mov ecx, dword ptr [rsp + 4]
cmp eax, ecx
cmovl eax, ecx
mov ecx, dword ptr [rsp]
cmp eax, ecx
cmovl eax, ecx
Similar with GCC, while MSVC makes a mess with a loop.
public int maximum(int a,int b,int c){
int max = a;
if(b>max)
max = b;
if(c>max)
max = c;
return max;
}
I think by "most efficient" you are talking about performance, trying not to waste computing resources. But you could be referring to writing fewer lines of code or maybe about the readability of your source code. I am providing an example below, and you can evaluate if you find something useful or if you prefer another version from the answers you received.
/* Java version, whose syntax is very similar to C++. Call this program "LargestOfThreeNumbers.java" */
class LargestOfThreeNumbers{
public static void main(String args[]){
int x, y, z, largest;
x = 1;
y = 2;
z = 3;
largest = x;
if(y > x){
largest = y;
if(z > y){
largest = z;
}
}else if(z > x){
largest = z;
}
System.out.println("The largest number is: " + largest);
}
}
#include<stdio.h>
int main()
{
int a,b,c,d,e;
scanf("%d %d %d",&a,&b,&c);
d=(a+b+abs(a-b))/2;
e=(d+c+abs(c-d))/2;
printf("%d is Max\n",e);
return 0;
}
I Used This Way, It Took 0.01 Second
#include "iostream"
using std::cout;
using std::cin;
int main()
{
int num1, num2, num3;
cin>>num1>>num2>>num3;
int cot {((num1>num2)?num1:num2)};
int fnl {(num3>cot)?num3:cot};
cout<<fnl;
}
Or This
#include "iostream"
using std::cout;
using std::cin;
int main()
{
int num1, num2, num3;
cin>>num1>>num2>>num3;
int cot {(((num1>num2)?num1:num2)>((num3>cot)?num3:cot)?((num1>num2)?num1:num2):((num3>cot)?num3:cot))};
cout<<cot;
}
The most efficient way to find the greatest among 3 numbers is by using max function. Here is a small example:
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int x = 3, y = 4, z = 5;
cout << max(x, max(y, z)) << endl;
return 0;
}
If you have C++ 11, then you can do it as follow:
int main() {
int x = 3, y = 4, z = 5;
cout << std::max({x, y, z}); << endl;
return 0;
}
If you are interested to use a function, so that you can call it easily multiple times, here is the code:
using namespace std;
int test(int x, int y, int z) { //created a test function
//return std::max({x, y, z}); //if installed C++11
return max(x, max(y, z));
}
int main() {
cout << test(1, 2, 3) << endl;
cout << test(1, 3, 2) << endl;
cout << test(1, 1, 1) << endl;
cout << test(1, 2, 2) << endl;
return 0;
}
Here is a small function you can use:
int max3(int a, int b, int c=INT_MIN) {
return max(a, max(b, c));
}
In C# finding the greatest and smallest number between 3 digit
static void recorrectFindSmallestNumber()
{
int x = 30, y = 22, z = 11;
if (x < y)
{
if (x < z)
{
Console.WriteLine("X is Smaller Numebr {0}.", x);
}
else
{
Console.WriteLine("z is Smaller Numebr {0}.", z);
}
}
else if (x > y)
{
if (y < z)
{
Console.WriteLine("y is Smaller number.{0}", y);
}
else
{
Console.WriteLine("z is Smaller number.{0}", z);
}
}
else
{
}
}
=================================================================
static void recorrectFindLargeNumber()
{
int x, y, z;
Console.WriteLine("Enter the first number:");
x = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number:");
y = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the third nuumnber:");
z = int.Parse(Console.ReadLine());
if (x > y)
{
if (x > z)
{
Console.WriteLine("X is Greater numbaer: {0}.", x);
}
else
{
Console.WriteLine("Z is greatest number: {0}.", z);
}
}
else if (x < y)
{
if (y > z)
{
Console.WriteLine("y is Greater Number: {0}", y);
}
else
{
Console.WriteLine("Z is Greater Number; {0}", z);
}
}
else
{
}
}
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int num1,num2,num3,maximum;
cout<<"Enter 3 numbers one by one "<<endl;
cin>>num1;
cin>>num2;
cin>>num3;
maximum=max(max(num1,num2),num3);
cout<<"maximum of 3 numbers is "<<maximum<<endl;
}
Related
I want to make a program that takes 4 numbers eg.(a, b, c and d) and checks if using arithmetic operators i can make the first 3 numbers result to the fourth number, like if the input is (3, 4, 5, 23) this will check out true because
3 + 4 * 5 = 23,So i want to make an array that has the operators and use a loop to check every possible combination, Hope i made it clear.
Edit:
Its actually codeforces problem, given 4 numbers. Check whether he could get the fourth number by using the arithmetic operators (+,−,×) between the other three numbers. Knowing that an operator can be used only once. in this format ->(a□b□c=d).My question was if there is a way to make it automatic or do i have to code every possibility manually So sorry for any confusion i may have caused.
You can't store the operators in an array, but you could make wrapper functions for them and store those in an array.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
funptr arr[] = { add, sub, mul, div };
You can then call them like:
(arr[1])(2, 1) // call sub(2, 1)
The parentheses around arr[1] aren't needed in this case, but I like to put them for clarity.
No. You'd have to write a program to work this out. You could store something like function pointers to the arithmetic operators in an array, but I don't think that would help solve your problem. You'd still have to write the code to solve your problem.
Adding onto #CoffeeTableEspresso's answer, you can also put those function pointers into a map.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
std::map<char,funptr> operators = {
{'+', add},
{'-', sub},
{'*', mul},
{'/', div}};
Then you can do
operators['+'](4,7);
Which might be a bit more readable, and you can iterate through these more easily.
I thought I would submit a compete answer. This works for positive numbers. It may take a bit more work to cover all the possibilities. And it does not answer to CoffeeTableEspresso's question about precedence. But it may help with your last question about if statements.
#include <iostream>
namespace {
auto add = [](int a, int b) {return a + b; };
auto sub = [](int a, int b) {return a - b; };
auto mult = [](int a, int b) {return a * b; };
auto divd = [](int a, int b) {return b ? a / b : -1; };
std::vector<int(*)(int, int)> ops = { add,sub,mult,divd };
}
int check(int* params)
{
for (size_t i = 0; i < 4; ++i)
for (size_t j = 0; j < 4; ++j)
{
auto result = ops[i](params[0], ops[j](params[1], params[2]));
if (params[3] == result)
return result;
else
std::cout << result << std::endl;
}
return -1;
}
int main()
{
int params[] = { 3, 4, 5, 23 };
std::cout << check(params);
}
Operators * / have a higher precedence than + -, so operator[i](A, operator[j](B, C)) solution doesn't really work.
You can write a little string calculator, and cycle through char-operators:
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
double calculate(std::string str)
{
// calculator there
return -1;
};
int main()
{
std::vector<char> op = {'+', '-', '*', '/'};
std::vector<int> a = { 96, 3, 10, 42 };
for (auto op1: op)
for (auto op2: op)
{
std::stringstream ss;
ss << a[0] << op1 << a[1] << op2 << a[2];
double result = calculate( ss.str());
if (std::abs(a[3] - result) < 1E-6)
std::cout << ss.str() << " = " << a[3];
else
std::cout << ss.str() << " = " << result << " != " << a[3];
}
}
Here is the C++ program i wrote to solve the above series:
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int factorial(int a)
{
if (a > 1)
return a * factorial(a - 1);
else
return 1;
}
float series(float x, int n, float b)
{
if (abs(pow(x, n) / factorial(n)) < pow(10, -6) || abs(pow(x, n) / factorial(n)) == pow(10, -6)) { return b; }
else return b = (pow(x, n) / factorial(n)) + series(x, n + 1, b);
}
int main()
{
float x;
cout << "Enter x: "<<endl;
cin >> x;
cout << "E^x = " << series(x,0,0);
system("pause");
return 0;
}
It works fine when abs(x) < 2 but when abs(x) >= 2 this error appears:
Unhandled exception at 0x00F02539 in 33b.exe: 0xC00000FD: Stack
overflow (parameters: 0x00000001, 0x00F22FF8). occurred
I want to know why does this happen and how can i fix it?
Your problem is too deep recursion. Consider loop instead.
float series(float x)
{
const float epsilon = 1e-6f;
double error = 1;
double res = 1.f;
int iter = 1;
while (abs(error) > epsilon) {
error *= (x / iter++);
res += error;
cout << error << endl;
}
return res;
}
int main()
{
cout << "E^x = " << series(3);
system("pause");
return 0;
}
To be clearer about what happens:
When you call a function inside another function, the context of the parent function is saved to make room for the new context. When you make millions of inception, the memory stack in charge to save these context is full and overflows.
This is a Stack Overflow.
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int factorial[200];
int Factorial(int a)
{ if(a>0){
factorial[a]=a * factorial[a-1];
return factorial[a];
}
else
factorial[a]=1;
return 1;
}
double series(double x, int n, double b)
{ double temp=(abs(pow(x, n)) / Factorial(n));
if (temp <= 0.000001) { return b; }
else return (temp + series(x, n + 1, b));
}
int main()
{
float x;
cout << "Enter x: "<<endl;
cin >> x;
cout << "E^x = " << series(x,0,0);
system("pause");
return 0;
}
umm this solution is working. all i did was i took your code removed abs(pow(x, n) / factorial(n)) wherever its repeating and intialised to a new variable temp. then instead of < || == u can directly put <=. and rather than invoking a a function to calculate .000001 every time you could just give that value to reduce time further. however i believe that the reason why the code may not have worked is too much recursion. so for factorials i used dynamic programming to reduce its complexity. the above code is working perfectly fine.
I need to count how many cubes of values between a and b (2 and 9 in this example) end with numbers between 2 and 5. Everything has to be done with recursion.
The output of this code is
part c = recc = 4
32767
0
It does not make sense to me. It calculates the value of n correctly, but then once asked to return it, returns either 0 or 32767, as if it was not defined.
Can anyone pinpoint the issue?
#include <iostream>
#include <string>
using namespace std;
void partb(int a, int b){
if(a<=b){
int p = (a*a*a)%10;
else if(p>=2 && p<=5){
cout<<a*a*a<<" ";
}
partb(a+1, b);
}
}
int recc(int n, int a, int b){
int p = (a*a*a)%10;
if(a>b){
cout<<"recc = " << n << endl;
return n;
}
else if(a<=b){
if(p>=2 && p<=5){
n++;
}
recc(n, a+1, b);
}
}
int partc(int a, int b){
int n = recc(0, a, b);
cout<<endl<< "part c = " << recc(0, a, b) << endl;
return n;
}
int main(){
int n=partc(2,9);
cout << n << endl;
return 0;
}
Not all control paths in your function return a value, so you were getting undefined behaviour when using the return value.
Now, this wasn't helped by the fact that the function itself is needlessly complicated. Let's rewrite it to use common practice for recursion:
int recc(int a, int b)
{
if (a > b) return 0;
int p = (a*a*a)%10;
int n = (p>=2 && p<=5) ? 1 : 0;
return n + recc(a+1, b);
}
Now your function is simpler. The recursion termination condition is right at the top. The function then decides whether a will contribute 1 or 0 to the count. And finally you return that value plus the count for a smaller range.
Notice how return n + recc(a+1, b); has broken the problem into a simple local solution combined with the recursive result of a reduced scope.
The invocation becomes simpler too, because you no longer have to pass in a redundant argument:
int partc(int a, int b)
{
int n = recc(a, b);
cout << endl << "part c = " << n << endl;
return n;
}
I wrote a simple C++ program that computes permutations/factorials in 2 different methods. The problem arises when I try to use the longer method (p1) with 20 and 2. Granted, "20!" is a HUGE number. Is there a limit with integers when calculating the factorial using the recursion method?
#include <iostream>
using namespace std;
int p1(int n, int r);
int p2(int n, int r);
int factorial(int x);
int main()
{
cout << p1(10, 8) << endl;
cout << p2(10, 8) << endl;
cout << p1(4, 3) << endl;
cout << p2(4, 3) << endl;
cout << p1(20, 2) << endl; // THE NUMBER PRINTS INCORRECTLY HERE
cout << p2(20, 2) << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
int p1(int n, int r) // long version, recursively calls factorial
{
return (factorial(n) / factorial(n - r));
}
int factorial(int x)
{
if (x == 0)
return 1;
else if (x > 0)
return (x * factorial(x - 1));
}
int p2(int n, int r) // shortcut, does arithmetic in for loop
{
int answer = n;
for (int i = 1; i < r; i++)
{
answer *= n - 1;
n--;
}
return answer;
}
20! is 2.4*10^18
You can check out a reference of limits.h to see what the limits are.
consider that 2^32 is 4.2*10^9. long int is usually a 32-bit value.
consider that 2^64 is 1.8*10^19, so a 64-bit integer will get you through 20! but no more. unsigned long long int should do it for you then.
unsigned long long int p1(int n, int r)
{
return (factorial(n) / factorial(n - r));
}
unsigned long long int factorial(unsigned long long int x)
{
if (x == 0)
return 1;
else if (x > 0)
return (x * factorial(x - 1));
}
unsigned long long int p2(int n, int r)
{
unsigned long long int answer = n;
for (int i = 1; i < r; i++)
{
answer *= n - 1;
n--;
}
return answer;
}
If you are allowed in this assignment, consider using float or double, unless you need absolute precision, or just need to get to 20 and be done. If you do need absolute precision and to perform a factorial above 20, you will have to devise a way to store a larger integer in a byte array like #z32a7ul states.
Also you can save an operation by doing answer *= --n; to pre-decrement n before you use it.
20! exceeds the integer range. Your shortcut function doesn't exceed simply because you don't calculate the whole faculty, but 20*19
If you really need it, you may create a class that holds a variable-length array of bytes, and define operators on it. In that case, only the available memory and your patiance will limit the size of numbers. I think Scheme (a LISP dialect) does something like that.
the point of this exercise is to multiply a digit of a number with its current position and then add it with the others. Example: 1234 = 1x4 + 2x3 + 3x2 + 4x1 .I did this code successfully using 2 parameters and now i'm trying to do it with 1. My idea was to use - return num + mult(a/10) * (a%10) and get the answer, , because from return num + mult(a/10) i get the values 1,2,3,4- (1 is for mult(1), 2 for mult(12), etc.) for num, but i noticed that this is only correct for mult(1) and then the recursion gets wrong values for mult(12), mult(123), mult(1234). My idea is to independently multiply the values from 'num' with a%10 . Sorry if i can't explain myself that well, but i'm still really new to programming.
#include <iostream>
using namespace std;
int mult(int a){
int num = 1;
if (a==0){
return 1;
}
return ((num + mult(a/10)) * (a%10));
}
int main()
{
int a = 1234;
cout << mult(a);
return 0;
}
I find this easier and more logically to do, Hope this helps lad.
int k=1;
int a=1234;
int sum=0;
while(a>0){
sum=sum+k*(a%10);
a=a/10;
k++;
}
If the goal is to do it with recursion and only one argument, you may achieve it with two functions. This is not optimal in terms of number of operations performed, though. Also, it's more of a math exercise than a programming one:
#include <iostream>
using namespace std;
int mult1(int a) {
if(a == 0) return 0;
return a % 10 + mult1(a / 10);
}
int mult(int a) {
if(a == 0) return 0;
return mult1(a) + mult(a / 10);
}
int main() {
int a = 1234;
cout << mult(a) << '\n';
return 0;
}