I'm New to C++ and I want to know if there's a way to add two fractions by using the LCM, as i want to display the added fractions in reduced form. I also can't use functions or string or thing of that nature. I attempted to answer it using GCD but this isn't the assignment question so i could some help.
Such as 3/8 + 5/12 = 19/24, i know this it the answer, i just don't know how to get c++ to display it
int main()
int num1,denom1,num2,denom2,num3,denom3,GCD,i;
while(denom1!=0 || denom2!=0)
{
cout<<"Enter Numerator of fraction one ";
cin>>num1;
cout<<"Enter Denominator of fraction one ";
cin>>denom1;
cout<<"Enter Numerator of fraction two ";
cin>>num2;
cout<<"Enter Denominator of fraction two ";
cin>>denom2;
num3 = (num1 * denom2) + (denom1 * num2);
denom3 = denom1 * denom2;
cout<<"The answer is "<<num3<<"/"<<denom3;
}
if (denom3 == 0)
{
exit;
}
for (i = 1; i <= num3 && i <= denom3; ++i)
{
if (num3 % i == 0 && denom3 % i == 0)
GCD = i;
}
cout <<"\n The added fraction is " << num3/GCD << "/" << denom3/GCD;
cout << endl;
return 0;
}
You probably want to implement something like
class Fraction{
private:
int numerator;
int denominator;
public:
Fraction (int n, int dn);
void reduce ();
Fraction add (Fraction a, Fraction b);
Fraction subtract (Fraction a, Fraction b);
}
I got this code. I bet it can be simplified, but I think you will understand it.
#include <iostream>
using namespace std;
int main()
{
int tempNum , tempDenom;
int denom1=8 , denom2=12 , denom3, num1=3 , num2=5, num3;
for(int i = 1 ; ;i++){ // this loop will work untill you find
multiplier for the first fraction
if ( (denom1 * i) % denom2 == 0){
denom3 = denom1 * i;
num1 = num1 * i;
break; // when you find it, you will end the
} //loop with break
}
for(int i = 1 ; ;i++){ // this loop will work untill you find
multiplier for the second fraction
if ( (denom2 * i) % denom1 == 0){
num2 = num2 * i;
num3 = num1 + num2;
break; // when you find it, you will end the
} loop with break
}
for (int i = num3 ; i > 1 ; i--){
tempNum = num3 % i; //the % gives you the rest of the divison
tempDenom = denom3 % i;
if(tempNum == 0 && tempDenom == 0){
num3 = num3 / i;
denom3 = denom3 / i;
break; // you have simplified the fraction
}
}
cout << "The result is : " << num3 << "/" << denom3;
}
Related
So I was trying to get the prime number between two numbers, it works fine but it also prints out odd numbers
int prime(int num1, int num2)
{
int sum{0};
while (num1 <= num2)
{
for (int i = 1; i <= num1; i++)
{
if (num1 % i == 0) //remainder needs to be zero
{
if (num1 % 2 == 0) continue; //continue the loop if the number is even
if (i * num1 == num1 && num1 / i == num1)
{//make sure it only prints prime numbers
cout << num1 << endl;
sum += num1;
}
}
}
num1++;
}
return sum;
}
Console log
I tried to make a for loop that iterates between 1 and N and if the remainder is zero it also checks if the number is even.. if it is then it continues the loop. and then i checked for prime numbers.. if (i * num1 == num1 && num1 / i == num1) i expected it to print out only prime numbers and last the sum of them but it also counts odd numbers
This if statement
if (i * num1 == num1 && num1 / i == num1)
{//make sure it only prints prime numbers
cout << num1 << endl;
sum += num1;
}
is always evaluated for any number when i is equal to 1.
So the code has a logical error.
At least there is no sense to start the for loop
for (int i = 1; i <= num1; i++)
with i equal to 1.
Pay attention to that prime numbers are defined for natural numbers that is for numbers of unsigned integer types.
I would write the function at least the following way
unsigned long long int sum_of_primes( unsigned int first, unsigned int last )
{
unsigned long long int sum = 0;
if (not ( last < first ))
{
do
{
bool prime = first % 2 == 0 ? first == 2 : first != 1;
for (unsigned int i = 3; prime && i <= first / i; i += 2)
{
prime = first % i != 0;
}
if (prime) sum += first;
} while (first++ != last);
}
return sum;
}
For example if in main to write this statement
std::cout << "sum_of_primes(0, 10) = " << sum_of_primes( 0, 10 ) << '\n';
then its output will be
sum_of_primes(0, 10) = 17
Indeed in this range [0, 10] prime numbers are 2, 3, 5, 7 and their sum is equal to 17.
How would I print the number of operations and time taken to compute Fibonacci numbers recursively versus that needed to compute them iteratively. Here is my code currently:
#include<bits/stdc++.h>
using namespace std;
int iterative(int n){
int num1 = 0, num2 = 1, num3, j;
cout<<num1<<" "<<num2<< " ";
if( n == 0)
return num1;
for (j = 2; j <= n; j++){
num3 = num1 + num2;
cout<<num3<<" ";
num1 = num2;
num2 = num3;
}
return num2;
}
int recursive(int num){
if (num <= 1)
return num;
return recursive(num-1) + recursive(num-2);
}
int main (){
// main method to test the function
int n;
cout << "Enter a value for n: ";
cin >> n;
printf("\nWhen n is %d ,the iterative method number is : %d", n,iterative(n));
getchar();
printf("\nWhen n is %d ,the recursive method number is : %d", n,recursive(n));
getchar();
return 0;
}
Try something like this. As mentioned above you should not using include #include<bits/stdc++.h> . If you want to know more about problems with that include you should read this.
#include <chrono>
#include <iostream>
int iterative(int n, int &cnt){
int num1 = 0, num2 = 1, num3, j;
std::cout<<num1<<" "<<num2<< " ";
if( n == 0)
return num1;
for (j = 2; j <= n; j++){
num3 = num1 + num2;
std::cout<<num3<<" ";
num1 = num2;
num2 = num3;
cnt++;
}
return num2;
}
int recursive(int num, int &cnt){
if (num <= 1)
return num;
cnt++;
return recursive(num-1, cnt) + recursive(num-2, cnt);
}
int main (){
// main method to test the function
int n;
int cnt = 0;
std::cout << "Enter a value for n: ";
std::cin >> n;
auto start = std::chrono::high_resolution_clock::now();
int iterativeNum = iterative(n, cnt);
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> duration = end - start;
printf("\nWhen n is %d , num of operation is : %d , time spent is : %f , the iterative method number is : %d", n, cnt, duration.count() ,iterativeNum);
getchar();
cnt = 0;
start = std::chrono::high_resolution_clock::now();
int recNum = recursive(n, cnt);
end = std::chrono::high_resolution_clock::now();
duration = end - start;
cnt = 0;
printf("\nWhen n is %d , num of operation is : %d , time spent is : %f , the recursive method number is : %d" , n, cnt, duration.count(), recNum);
getchar();
return 0;
}
I am trying to find a reversed number and check that it is a palindrome or not from a different approach but I was getting a right reversed number up to two digits and if the digits are more than two then I am getting wrong output. I cannot understand why is this so as I think my code is right.
below is the code
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int num, rem, t, add;
cin >> t;
while (t--) {
int total = 0, count = 0, i = 1, quo = 0;
cin >> num;
quo = num;
while (quo > 9) //count determiner
{
quo = quo / 10;
++count;
}
while (count >= 0) //reverse number saved in total
{
int den = pow(10, i);
rem = (num % den);
add = rem / pow(10, i - 1);
total = total + (add * pow(10, count));
++i;
--count;
}
if (total == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
please help me to know where I am going wrong in this code.
I don't understand your code. so i assumed by myself and wrote code.I assume that there will be no negative number and if there will be then i rid off negative sign. please provide desire output for negative number.
#include <iostream>
using namespace std;
int main()
{
//int num, rem, t, add;
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
int num = abs(n);
if (n < 0)
{
n = abs(n);
}
int res{ 0 };
while (n > 0)
{
res *= 10;
int rem = n % 10;
res += rem;
n /= 10;
}
if (res == num) {
cout << "Palindrome"
<< "\n";
}
else {
cout << "Not a Palindrome"
<< "\n";
}
}
return 0;
}
ouptut of above code:
4
-191
Palindrome
232
Palindrome
123
Not a Palindrome
561
Not a Palindrome
Your code to reverse a number is very convoluted, as it uses pow (a floating point function) to get each digit. This is totally unnecessary if you look for the pattern of how to reverse an integer.
Simple addition, multiplying by 10, and modulus is all that's necessary to do this. Note that I created a function, so that it is easy to follow:
#include <cmath>
#include <iostream>
int reverse_int(int num)
{
int total = 0;
// take care of negative by using absolute value
int tempNum = abs(num);
while (tempNum > 0)
{
total = (total*10) + (tempNum % 10);
tempNum /= 10;
}
return (num < 0)?-total:total;
}
int main()
{
int num = 1234321;
if ( num == reverse_int(num))
std::cout << num << " is a palindrome\n";
else
std::cout << num << " is not a palindrome\n";
int num2 = 123;
if ( num2 == reverse_int(num2))
std::cout << num2 << " is a palindrome\n";
else
std::cout << num2 << " is not a palindrome\n";
}
Output:
1234321 is a palindrome
123 is not a palindrome
The loop is very simple if you follow what is going on:
number = 123 (Assume this is our number)
total = 0;
Loop while (number > 0):
First iteration:
total = (total * 10) + (number % 10) --> (0 * 10) + (0 % 3) --> 3
number /= 10 --> 12
Second iteration:
total = (total * 10) + (number % 10) = (3 * 10) + (12 % 10) --> 32
number /= 10 --> 1
Third iteration:
total = (total * 10) + (number % 10) = (32 * 10) + (1 % 10) --> 321
number /= 10 --> 0 (Stop the loop)
total = 321
At the end of the function, we just return the value, and make it negative if the original number was negative.
You are not checking if the input was valid. So if we leave that aside and assume the input is a valid integer then you can use a std::string and reverse it via std::reverse:
#include <string>
#include <algorithm>
#include <iostream>
int main() {
std::string input;
std::cin >> input;
std::string reverse = input;
std::reverse(reverse.begin(),reverse.end());
if (input == reverse) std::cout << "Palindrome number"
}
How can i remove all digits from number before finding specific digit.
Let's say i want to get all digits after digit 1 (1-included)
Example: 3543125 - i want to get digits 125
i started doing this:
int n, result;
cout << "Please enter number: ";
cin >> n;
while (n>0)
{
n = n % 10;
}
to get last digit, but i don't know how you can save it in variable and then add the second digit to it.
Can someone please explain, how can i solve this?
Here is an algorithm I didn't test it but it works {only with loops and if}
int num = 3543125;
int temp = 0;
do //get the result in reverse number
{
temp += num % 10;
temp *= 10;
num /= 10;
if (num % 10 == 1)
temp += 1;
} while (num % 10 != 1);
int result = 0;
while (temp > 0) //reverse the temp number to result
{
result = result * 10 + (temp % 10);
temp = temp / 10;
}
cout << result; // = 125
Try this one. (too simple :-) )
#include <math.h>
int n,a, result=0;
cout << "Please enter number: ";
cin >> n;
cout << "Please enter number of digits: ";
cin >> a;
int b=a;
while(b>0) {
result += n%10 * pow(10,a-b--);
n=n%10;
}
std::cout<<"result: "<<result;
You create a program that displays the sum of even integers between and including two numbers entered by the user ..
ex) 2 and 7 = the sum of 12 (2+4+6)
this is what i have so far! butt if u can just put me in the right direction that would be helpful
//Advanced30.cpp - displays the sum of the even integers between and
//including two numbers entered by the user
//Created/revised by <your name> on <current date>
#include <iostream>
using namespace std;
int main()
{
// declare variables
int num1 = 0;
int num2 = 0;
int sum= 0;
cout << "Enter the First Number:" << endl;
cin >> num1;
cout << "Enter the Second Number:" << endl;
cin >> num2;
if ( num1 > num2)
{
cout << "Invalid entry. Final number must be less than the first number. Please try again." << endl;
}
for ( int sum = (((num1 + 1)/2)*2); num1 <= (((num2 + 1)/2)*2) ; sum = 2 + (((num1 + 1)/2)*2) )
return 0;
} //end of main function
In your for loop it should be like this.
double sum = 0.0;
for(i = num1; i <= num2; i++){
if(i % 2 == 0){ // Is our number even
sum += i;
}
}
That's it and it print out sum.
I would simplify your for loop
for(int i = num1; i <= num2; i++) {
if(i % 2 == 0) sum += i;
}
This will look at twice as many numbers, but honestly that's not all that much more expensive.
You could also do it in O(1) time by taking advantage of the fact that the sum 1..n == n*(n+1)
Here's a very simple example in Java, translating it to C++ won't be too difficult I hope :) no C++ compiler on this machine :-X
import java.util.*;
class DoubleSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int low = (num1 - 1)/ 2;
int high = num2 / 2;
int sumLow = (low*(low + 1));
int sumHigh = (high*(high + 1));
int sum = sumHigh - sumLow;
System.out.println(sum);
}
}
You are using the same variable to control the for loop and to the sum, this won't work. Try this:
int even1 = num1 % 2 == 0 ? num1 : num1+1;
int even2 = num2 % 2 == 0 ? num2 : num2-1;
for (int i = even1; i <= even2; i += 2) sum += i;
Note that you don't really need a for loop:
int even1 = num1 % 2 == 0 ? num1 : num1+1;
int even2 = num2 % 2 == 0 ? num2 : num2-1;
// how many numbers you will sum (remember they are even, so we need to divide by 2)
int count = 1 + (even2 - even1)/2;
sum = (even1 + even2) * (count/2);
if (count % 2 == 1) sum += (even1 + even2)/2;
for(int i = num1; i <= num2; i++)
{
if(!(i & 1))
sum += i;
}
Your code would end up in an infinite loop.
Look at the for() loop. You have the condition
num1 <= (((num2 + 1)/2)*2)
to determine whether your loop terminates. However, since num1 itself is never incremented, and num1 < num2 is guaranteed, this condition will always be true - which means your for loop would never end. I would also suggest using a separate looping variable.