print largest number out of 4 numbers optimize - c++

#include <iostream>
using namespace std;
int main()
{
int num1,num2,num3,num4;
int x;
int y;
cin>>num1>>num2>>num3>>num4;
if (num1 > num2)
{
x=num1;
}
else
{x = num2;
}
if(num3>num4)
{y = num3;
}
else
{
y= num4;
}
if (x>y)
{cout<<"the largest number is:"<<x;
}
else
{
cout<<"the largest number is :"<<y;
}
return 0;
}
this is my code to print largest number out of 4 numbers.
the question is that i am asked to optimize or compact the solution.
i tried but could not find another way to write such program.Can any one help me to optimize the solution and make it better..
ignore syntax errors..

Could be as simple as this:
int max = std::max( std::max( num1, num2 ), std::max( num3, num4 ) );

#include<iostream>
using namespace std;
int main() {
int x, m;
cin >> x;
m = x;
for (int i = 0; i < 3; ++i) {
cin >> x;
m = m > x ? m : x;
}
cout << "The largest number is: " << m << endl;
return 0;
}
Use loops.

One approach would be to store the values in an array and iterate over it:
int num[4];
cin >> num[0] >> num[1] >> num[2] >> num[3];
int max = num[0];
for (int i = 1; i < 4; ++i) {
if (num[i] > max) {
max = num[i];
}
}
cout << "The largest number is:" << max << endl;

Since C++11, you may directly do
const int biggest = std::max({num1, num2, num3, num4});

Try this :)) in this case i do not use std library. Just use an if-else statement like below. if(a > b) then return a else b.
Other case, we can create an array and request input to the user. First we set the first element in this array is MAX value. Use a loop and check. if current element is larger than MAX then we update the MAX value to the current value.
int maxOfTwoNumber(int a, int b){ return a>b? a : b; }
int maxOfFourNumber(int a, int b, int c, int d){
return maxOfTwoNumber(maxOfTwoNumber(a, b), maxOfTwoNumber(c, d));
}

Related

Pick a number say 3 so you can enter 3 numbers then substract the maximum from the min

I tried changing a lot of integers and stuff but it didn't work and it gives me a random number like 53289432 even tho lets say i put in 3:5,1,2 it should output 3 since 5-2 is 3.
#include <iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int x[n];
int mn;
int mx;
for(int i=1;i<n;i++)
{
cin>>x[i];
for(int j=1;j<n;j++)
{
if(x[i]>x[j]);
}
{
x[i]=mn;
}
}
for(int i=1;i<n;i++)
{
for(int j=1;j<n;j++)
{
if(x[i]<x[j]);
}
{
x[i]=mx;
}
}
cout<<mx-mn;
}
You don't need an array:
int smallest = 0;
int largest = 0;
std::cout << "Enter quantity: ";
int quantity;
std::cin >> quantity;
if (quantity < 1)
{
std::cerr << "Invalid quantity.\n";
return 1;
}
std::cout << "Enter number: ";
std::cin >> smallest;
largest = smallest;
for (int i = 1; i < quantity; ++i)
{
std::cout << "Enter number: ";
int number;
std::cin >> number;
if (number < smallest) smallest = number;
if (number > largest) largest = number;
}
std::cout << "maximum from minimum: " << (smallest - largest) << "\n";
std::cout << "minimum from maximum: " << (largest - smallest) << "\n";
The above code uses a running minimum/maximum, so no arrays are needed.
No need for variable length arrays or having to figure out the array capacity at compile time.
Your code carries several holes,
Firstly,
for(int i=1;i<n;i++)
{
cin>>x[i];
This won't take n integers, it will only take (n-1) integers as input. You need to initialise i=0, for n integers;
Secondly,
for(int i=1;i<n;i++)
{
cin>>x[i];
for(int j=1;j<n;j++)
{
if(x[i]>x[j]); //This will compare with garbage when i=1 and j>1
}
{
x[i]=mn;
}
}
Your comparison, will only be valid for first iteration of i=1 and j=1, after j>1, it will pick garbage value, since, you haven't taken any input yet.
It is suggested, to first take all the inputs, then do the comparison, or other operations.
Here is my solution
I think this is what you are trying to do!
#include <iostream>
#include <climits>
using namespace std;
int main()
{
int n;
cin>>n;
int x[n];
int mn;
int mx;
//First take the inputs in array x
for(int i=0;i<n;i++)
{
cin>>x[i];
}
//Find maximum and store it in mx
mx = INT_MIN; //This stores minimum in mx variable (climits)
for(int j=0;j<n;j++)
{
if(mx<x[j])
mx=x[j];
}
//Find minimum and store it in mn
mn = INT_MAX; //This stores maximum in mn variable (climits)
for(int j=0;j<n;j++)
{
if(mn>x[j])
mn=x[j];
}
int ans = mx - mn;
cout<<ans<<endl;
}
There is a better solution where you don't use extra space(array), and by using only 2 variables, you can find the difference. But I would recommend you to first understand this concept, and take a look, how array works, before moving towards any optimised solution.

find minimum number of ways to write the sum of square of value from 0 to n equals n

#include<bits/stdc++.h>
using namespace std;
vector<int> memo;
class Solution{
public:
int minimum(int a , int b){
if(a>b) return b;
return a;
}
public:
int MinSquares(int n , vector<int> memo)
{
if(n<= 3){
return n;
}
if(memo[n]>-1) {
return memo[n];
}
int m = n ;
for(int i = 1 ; n-(i*i)>=0; i++){
m = minimum(m, MinSquares(n - i*i , memo) + 1 );
}
memo[n]=m;
return memo[n];
}
};
// { Driver Code Starts.
int main(){
int tc;
cin >> tc;
while(tc--){
int n;
cin >> n;
Solution ob;
vector<int> memo;
memo.assign(n+1 ,-1);
memo[0]=0;
memo[1]=1;
int ans = ob.MinSquares(n , memo);
cout << ans <<"\n";
}
return 0;
}
I know that recurrence relation and tried solving it with using pen and paper.
when trying output 100 it taking much more time than usual . I have spend at least 4 hour why there is no error in syntax and it is giving result for less than 100 .
please help.
It is not clear what you want to do. You claimed total number of ways, but in practice, you code calculates the minimum length of a sum of squares equal to n
Concerning the efficency issue that you mentioned, the problem is here:
int MinSquares(int n , std::vector<int> memo)
You are continuoulsly copying memo. This is solved by using a reference
int MinSquares(int n , std::vector<int>& memo)
#include <iostream>
#include <vector>
//vector<int> memo;
class Solution{
public:
int minimum(int a , int b){
if(a>b) return b;
return a;
}
public:
int MinSquares(int n , std::vector<int>& memo) {
if (n <= 3){
return n;
}
if(memo[n] > -1) {
return memo[n];
}
int m = n ;
for(int i = 1 ; n-(i*i)>=0; i++){
m = minimum (m, MinSquares(n - i*i , memo) + 1);
}
memo[n] = m;
return memo[n];
}
};
// { Driver Code Starts.
int main(){
int tc;
std::cin >> tc;
while(tc--){
int n;
std::cin >> n;
Solution ob;
std::vector<int> memo;
memo.assign(n+1 ,-1);
memo[0] = 0;
memo[1] = 1;
int ans = ob.MinSquares(n , memo);
std::cout << ans <<"\n";
}
return 0;
}

creating an upwards series in c++

Screenshot of my code
Hey, I have just started learning C++ and I am trying to get it to sum the series:
K+N−1∑n=K [-1^(n)/(n+1)2]
I have managed to get it to tell me the nth term previously, but now I would like to for each term in the series, starting with the kth and going in sequence to the last (k+n-1st), add this term to the running sum.
I need to use a function direct_up() which uses the function term(). I defined initially and test it in the main.
I know I am missing something and am a bit confused about how to use the functions and that I may have made a few mistakes. So I would be very grateful for some advice or help. I have attached a picture of what I have done so far, as well as typed it below.
using namespace std;
double term(int n) {
double y;
if(n%2==1) {
y = -1.0/((n+1.0)*(n+1.0));
} else {
y = 1.0/((n+1.0)*(n+1.0));
}
return y;
}
double direct_up(int k, int n) {
int startingnumber = k;
for (int i = startingnumber; i <= k+n; i++) {
cout << n << term(n) << endl;
}
return n;
}
int main() {
double n;
int k;
cout.precision(16);
cout << "enter number of terms";
cin >> n;
cout << "enter a value for k";
cin >> k;
cout << "here is the value" << direct_up(k,n);
return 0;
}
This is what you want to do:
double direct_up(int k, int n)
{
int startingnumber = k;
double sum = 0;
for (int i = startingnumber; i <= k+n; i++) {
sum += term(i);
}
return sum;
}
Here's how to do it without keeping your own running sum as you asked in your comment:
#include <vector>
#include <numeric>
double direct_up(int k, int n)
{
int startingnumber = k;
std::vector<double> terms;
for (int i = startingnumber; i <= k+n; i++) {
terms.push_back(term(i));
}
return accumulate(terms.begin(), terms.end(), 0.0);
}

Using Lambda Expression To Code An Exponent In C++

How can I write an "X to the power of k" procedure in C++? (k is a positive integer)
I did the same thing in python, and it was a breeze, but in C++, I don't even know where to begin.
How can I write an "X to the power of k" procedure in C++? (k is a positive integer)
Write a short loop in a function like
int pow(int X, int k) {
int result = 1;
for(int i = 0; i < k; ++i) result *= X;
return result;
}
It's easy to express this in a lambda as well:
auto pow = [] (int X, int k) {
int result = 1;
for(int i = 0; i < k; ++i) result *= X;
return result;
};
cout << pow(5,3);
See a working sample please.
Ummm, maby try this:
#include <iostream>
#include<cmath> //adds math functions: power, square root etc.
using namespace std;
int main(){
int x;
int k;
cin >> x;
cin >> k;
x = pow(x, k);
cout << "\nX to the power of k: " << x << endl << endl;
return 0;
}

Can't increase range of numbers in a program in C++

Here is the question:
Comparing two numbers written in index form like 2^11 and 3^7 is not difficult, as any calculator would confirm that 2^11=2048<3^7=2187.
However, confirming that 632382^518061>519432^525806 would be much more difficult, as both numbers contain over three million digits.
You are given N base exponent pairs, each forming a large number you have to find the Kth smallest number of them. K is 1−indexed.
Input Format
First line containts an integer N, number of base exponent pairs. Followed by N lines each have two space separated integers B and E, representing base and exponent.
Last line contains an integer K, where K<=N
Constraints
1≤N≤105
1≤K≤N
1≤B≤109
1≤E≤109
No two numbers are equal.
Here is my code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N,i = 0,k,j=0,x,m;
long long int *arr,*arr2,*arr3;
cin >> N;
arr = (long long int *)malloc(sizeof(long long int)*2*N);
arr2 = (long long int *)calloc(N,sizeof(long long int));
arr3 = (long long int *)calloc(N,sizeof(long long int));
x = 2*N;
while(x>0)
{
cin >> arr[i];
i++;
x--;
}
cin >> k;
for(i=0;i<2*N;i+=2)
{
arr2[j] = pow(arr[i],arr[i+1]);
j++;
}
arr3 = arr2;
sort(arr2,arr2+N);
for(i=0;i<N;i++)
{
if(arr3[i] == arr2[k-1])
{
m = i;
break;
}
}
cout << arr[2*m] << " " << arr[2*m + 1];
return 0;
}
The program works for small numbers only, can't make it work for large numbers. what to do?
Maybe you are generating an overflow on the big numbers. You could consider using a multiprecision arithmetic library such as https://gmplib.org/. I haven't used this library myself.
Have a look at this post How to detect integer overflow? on how to detect integer overflow.
From your choosing of long long int type I guess you calculated the a^b of the numbers in order to sort them, which leads to very big numbers and may lead to overflow.
Note that in order to sort the numbers there is no need for this calculation, for knowing if a^b > d^c it is sufficient to check log(a^b) > log(c^d) and therefore b*log(a) > d*log(c).
And it's better to use a struct or class to create a data structure for this big numbers.
This is the code for it:
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
struct BigNumber{
int base;
int exponent;
};
int Compare(BigNumber x, BigNumber y);
void Sort(BigNumber* arr, int N);
int main() {
int N,i = 0,k;
BigNumber *numbers;
cout<<"\nEnter N:";
cin >> N;
numbers = (BigNumber *)calloc(N,sizeof(BigNumber));
for(i=0; i<N; i++)
{
cout<<"\nEnter base and exponent for number "<<i<<":";
cin >> numbers[i].base>>numbers[i].exponent;
}
cout<<"\nEnter K:";
cin >> k;
Sort(numbers,N);
cout << "Kth number is :" << numbers[k].base << "^" << numbers[k].exponent;
return 0;
}
void Sort(BigNumber* arr, int N){
for(int i=0; i< N; i++ ){
for(int j=0; j< N; j++){
if(Compare(arr[i], arr[j])<0){
BigNumber temp = arr[j];
arr[j] = arr[i];
arr[i] = arr[j];
}
}
}
}
int Compare(BigNumber x, BigNumber y){
double X = x.exponent * log10(x.base);
double Y = y.exponent * log10(x.base);
return X == Y? 0: X > Y ? 1: -1;
}
I changed the code a little. Only problem I was having was I was calculating the exponent rather than comparing log of exponent.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N,i = 0,k,j=0,x,m;
int *arr;
double *arr2,*arr3;
cin >> N;
arr = (int *)malloc(sizeof(int)*2*N);
arr2 = (double *)calloc(N,sizeof(double));
arr3 = (double *)calloc(N,sizeof(double));
x = 2*N;
while(x>0)
{
cin >> arr[i];
i++;
x--;
}
cin >> k;
for(i=0;i<2*N;i+=2)
{
arr2[j] = arr[i+1]*log10(arr[i]);
j++;
}
for (i = 0; i < N; i++) {
arr3[i] = arr2[i];
}
sort(arr2,arr2+N);
for(i=0;i<N;i++)
{
if(arr3[i] == arr2[k-1])
{
m = i;
break;
}
}
cout << arr[2*m] << " " << arr[2*m + 1];
return 0;
}