I'm trying to write a function that will find the reverse of a number, so if 1234 is input, the reverse is 4321.
#include <iostream>
using namespace std;
int reverse(int);
int main()
{
cout << "This is the special difference calculator. Please enter
positive integers: " << endl;
reverse();
}
int reverse(int num)
{
int num, remainder, reversenum;
cin >> num;
while (num != 0)
{
remainder = num % 10;
reversenum = reversenum * 10 + remainder;
}
return reversenum;
}
I also tried making a variable in main and setting it equal to reverse(int) but it showed it was wrong. I honestly have no idea what I'm doing so any help would be greatly appreciated!
There are a few logic errors in your code. Try the following code ( please note the comments ):
#include <iostream>
using namespace std;
int reverse();
int main()
{
cout << "This is the special difference calculator. Please enter positive integers: " << endl;
reverse();
}
int reverse()
{
int num, remainder, reversenum=0;//reversenum should be initialized to zero
cin >> num;
while (num != 0)
{
remainder = num % 10;
num = num/10; // Add this line so that while statement works correctly
reversenum = reversenum * 10 + remainder;
}
return reversenum;
}
You still do not understand how functions work.
Your logic was wrong (as far I was concerned)
I coded this for 2 digit numbers.
I left you the math equations for 3, 4, and 5 digit numbers. Use nested loops or input manipulation to choose the correct equation. Read the following stuff to learn more about functions. Stack Overflow is not for homework help, next time do more reading and try more in your code before asking for help.
Read: http://www.cplusplus.com/doc/tutorial/functions/
#include <iostream>
using namespace std;
int rev_function (int num)
{
int r;
//For 2 digit numbers
r = (10)*(num % 10) + (num - (num % 10)) / 10 ;
//For 3 digit numbers
//f(x) = (100)(x % 10) + ((x - (x % 10)) % 100) + (x - (x % 100)) / 100
//For 4 digit numbers
//f(x) = (1000)(x % 10) + ((x - (x % 10)) % 100) * 10 + ((x - (x % 100)) % 1000) / 10 + (x - (x % 1000)) / 1000
//For 5 digit numbers
//f(x) = (10000)(x % 10) + ((x - (x % 10)) % 100) * 100 + ((x - (x % 100)) % 1000) + ((x - (x % 1000)) % 10000) / 100 + (x - (x % 10000)) / 10000
return r;
}
int main ()
{
int z;
int num;
cout << "\nThis is the special difference calculator.";
cout << "\n Please enter positive integers: ";
cin >> num;
z = rev_function (num);
cout << "The result is " << z;
}
So the output would be:
This is the special difference calculator.
Please enter positive integers: 12
The result is 21
Related
4 integers are given (all no more than 10^6): m, n, k, l. If m % n == k or m % n == l, then print 1, else any other number. Conditional operators cannot be used!
Examples:
12 8 3 4 // input
1 // output
0 5 1 2 // input
0 // output
I wrote this code:
#include <iostream>
using namespace std;
int main()
{
int m, n, k, l;
cin >> m >> n >> k >> l;
cout << ((1 / (((m % (n + 1 / (n + 1))) - k) * ((m % (n + 1 / (n + 1))) - k) + 1)) - 1) * ((1 / (((m % (n + 1 / (n + 1))) - l) * ((m % (n + 1 / (n + 1))) - l) + 1)) - 1) + 1;
return 0;
}
But it does not work for all cases. For example, 0, 0, 0, 0 gives 1, but should give any other number.
Please help.
Note that there is no answer for n == 0 because division by zero is undefined.
In the other cases, since true prints as "1" and false as "0" by default,
cout << (m % n == l || m % n == k);
should do it.
what i understand from your question you are checking for 2 conditions, so after taking the input from the user we can check those conditions and assign value of val integer to 1 if that condition is true, else it will be 0 as initialized.
int m, n, k, l;
int val =0;
cin >> m >> n >> k >> l;
if(m % n == k || m % n == l){
val = 1;
}
cout << val ;
From what I understand I think you are trying to compare the modulus of two numbers with the other two inputs and if the result matches you want 1 as output otherwise 0
this will help you achieve it
#include <iostream>
using namespace std;
int main()
{
int m, n, k, l;
cin >> m >> n >> k >> l;
if(m%n == k || m%n == l)
{
count << 1
}
else
{
count << 0
}
return 0;
}
I was creating a program to find the solution to the series x - x^3/3! + x^5/5! - ... up to a certain term. The program is working but it is giving me wrong answers. Suppose if I take x = 5 and I wanted to find the sum up to 3 terms, it should give me 10.207(approx). But it is giving me an output of -15.8333. So please tell me where is the logical error in this program? I tried my best to find the error but I couldn't.
Here is the program:
#include <iostream>
#include <cmath>
using namespace std;
int N;
unsigned long long int factorial(int x);
long double evaluate(int x, int y = 1, int i = 1) {
if (i >= N) return 0;
if (i % 2) return pow(x, y)/factorial(y) - evaluate(x, y + 2, i + 1);
return pow(x, y)/factorial(y) + evaluate(x, y + 2, i + 1);
}
int main() {
int x;
cout << "Please enter a number: ";
cin >> x;
cout << "Please enter the number of terms: ";
cin >> N;
long double result = evaluate(x);
cout << "The evaluation result of the series is " << result << endl;
}
unsigned long long int factorial(int x) {
if (x < 0) return -1;
if (x == 0) return 1;
return x * factorial(x - 1);
}
I think the bugs are in the evaluate function:
long double evaluate(int x, int y = 1, int i = 1) {
if (i > N) return 0;
if (i % 2) return pow(x, y) / factorial(y) + evaluate(x, y + 2, i + 1);
return -pow(x, y) / factorial(y) + evaluate(x, y + 2, i + 1);
}
I have to print 8 terms of the sequence as
1, 2, 4, 8, 16, 22, 26, 38, ....
I have completed my logic till 16 that every new term is the previous term multiplied by 2. And after 16 the logic is that we divide that part into two as
26 = 22 + (2 * 2)
Till now what I have done is
int x = 1, num, num1, n = 1;
while (n <= 10)
{
while (n <= 4)
{
if (n == 1)
{
cout << x << ", ";
}
num = x % 10;
num1 = num % 10;
x = x * 2;
cout << x << ", ";
n++;
}
if (x == 16)
{
num = x % 10;
num1 = num % 10;
x = x + (num * num1) - 30;
cout << x << ", ";
}
else
{
num = x % 10;
num1 = num % 10;
x = x + (num * num1);
cout << x << ", ";
}
n++;
}
Apparently we just add the product of all digits to current number. That works fine for 1, 2, 4, 8 as well (e. g. 4 = 2 + (2)), so no need to have any special handling. However, apparently we need to ignore zeros, otherwise we wouldn't change after 102 any more...
So we can simplify the altorithm quite a bit:
unsigned int number = 1; // start value
std::cout << number; // OK, would require special handling for n == 0...
while(n--) // you could ask the user to input n or just set it to 10
// (I consider this variant a bit more elegant)
{
unsigned int product = 1;
unsigned int tmp = number;
// now iterate as long as you have more digits!
while(tmp)
{
unsigned int modulo = tmp % 10;
tmp /= 10;
// neat little trick: if modulo != 0, comparison is false, which is
// converted to 0, which is neutral for OR operation; otherwise, we
// get 0 | 1, which is neutral for multiplication...
product *= modulo | (modulo == 0);
}
number += product;
std::cout << ", " << number;
}
This would work fine even for fare more numbers than just the first ten ones (until overflow of either the product or the sum occurs...).
I am getting two warning (narrowing conversion && control may reach end of non-void function) with the following code. The code compiles however, when I run it it gives this message : Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
The code is compiled using CLion on Ubuntu
// calculate F(n) mod m
#include <iostream>
#include <cmath>
long long Fiobonacci(long long n) { // Fast calculation of Fibonacci number using 'fast doubling'
if (n == 0)
return 0;
else if (n % 2 == 0)
return Fiobonacci(n / 2) * (2 * Fiobonacci(n / 2 + 1) - Fiobonacci(n / 2));
else
return std::pow(Fiobonacci((n + 1) / 2), 2) + std::pow(Fiobonacci((n - 1) / 2), 2);
}
long long GetPissanoPeriod(long long m){
for (long long i = 0; i <= 6 * m ; ++i){
if (Fiobonacci(i) % m == 0){ // if an element is zero it might be followed by a 1
if(Fiobonacci(i+1) % m == 1)
return i+1;
}
}
}
int main() {
long long n, m;
std::cin >> n >> m;
long long period = GetPissanoPeriod(m);
long long res = Fiobonacci(n % period) % m;
std::cout << res << 'n';
}
See the modified code below.
#include <iostream>
#include <cmath>
using namespace std;
long long pow2(long long x)
{
return x * x;
}
long long Fibonacci(long long n) { // Fast calculation of Fibonacci number using 'fast doubling'
if (n == 0)
return 0;
else if(n <= 2)
return 1;
else if (n % 2 == 0)
return Fibonacci(n / 2) * (2 * Fibonacci(n / 2 + 1) - Fibonacci(n / 2));
else
return pow2(Fibonacci((n/2 + 1) / 2), 2) + pow2(Fibonacci((n / 2)), 2);
}
long long GetPisanoPeriod(long long m){
for (long long i = 2; i <= m * m ; ++i){
if (Fibonacci(i) % m == 0){ // if an element is zero it might be followed by a 1
if(Fibonacci(i+1) % m == 1){
return i - 1;
}
}
}
return 1;
}
int main() {
long long n, m;
std::cin >> n >> m;
long long period = GetPisanoPeriod(m);
long long res = Fibonacci(n % period) % m;
std::cout << "res" << res<<endl;
}
control may reach end of non-void function error is due to not returning value from GetPisanoPeriod. as pointed out by #JaMiT
The segmentation fault was due to the incorrect termination condition of function Fibonacci.
Fibonacci series is defined as below.
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1
Meaning there should be a termination condition for n = 0 and n = 1.
For n = 2 You don't have to call recursion can simply return 1.
Other than that, There were corrections in Fibonacci calculation formula as you can see.
In GetPisanoPeriod The control has to start from 2. otherwise it would always return 0.
I'm trying to implement the Bulls & Cows game and I have a logic problem. I am explicitly checking if each digit is either equal to a digit in the corresponding index (bulls) or at other indexes (cows). The value that I check with (4321) should yield "0 bulls and 4 cows" but it instead gives me "0 bulls and 3 cows.
Here is my code (and I apologize for the code repetition. I am also wondering if anyone has recommendations to make this code smaller):
#include <iostream>
#include <vector>
using namespace std;
int main() {
int guessValue = 1234;
int guess;
int bulls = 0;
int cows = 0;
cout << "Enter a 4 digit guess: ";
cin >> guess;
int firstValue = (guess % 10000) / 1000;
int secondValue = (guess % 1000) / 100;
int thirdValue = (guess % 100) / 10;
int fourthValue = guess % 10;
if (firstValue == ((guessValue % 10000) / 1000)) {bulls += 1;}
else if(firstValue == ((guessValue % 1000) / 100) ||
firstValue == ((guessValue % 100) / 10) ||
firstValue == (guess % 10))
{cows += 1;}
if (secondValue == ((guessValue % 1000) / 100)) {bulls += 1;}
else if (secondValue == ((guessValue % 10000) / 1000) ||
secondValue == ((guessValue % 100) / 10) ||
secondValue == (guess % 10))
{cows += 1;}
if (thirdValue == ((guessValue % 100) / 10)) {bulls += 1;}
else if (thirdValue == ((guessValue % 10000) / 1000) ||
thirdValue == ((guessValue % 1000) / 100) ||
thirdValue == (guess % 10))
{cows += 1;}
if (fourthValue == (guessValue % 10)) {bulls += 1;}
else if (fourthValue == ((guessValue % 10000) / 1000) ||
fourthValue == ((guessValue % 1000) / 100) ||
fourthValue == (guessValue % 100) / 10)
{cows += 1;}
cout << bulls << " bulls and " << cows << " cows" << endl;
}
I am also wondering if anyone has recommendations to make this code smaller
First of all use std::vector to keep separate digits:
std::vector<int> split( int v )
{
std::vector<int> r;
while( v ) {
r.push_back( v % 10 );
v /= 10;
}
return r;
}
Second, use standard algo std::count_if:
auto bulls = std::count_if( guessv.begin(), guessv.end(),
[it = targetv.begin()]( int i ) mutable
{ return i == *it++; } );
auto cows = std::count_if( guessv.begin(), guessv.end(),
[s = std::set<int>{ targetv.begin(), targetv.end() }]( int i )
{ return s.count( i ); } );
second one is actually counts cows and bulls, so it needs to be adjusted:
cows -= bulls;
live example
2 concepts that absolutely you need to master: loops and functions. First create some helpful functions.
These are the functions you could built your program upon:
int get_digit(int number, int order)
with example test cases:
get_digit(7895, 0) == 5
get_digit(7895, 1) == 9
get_digit(7895, 2) == 8
get_digit(7895, 3) == 7
then:
bool has_digit(int number, int digit)
with example test cases:
has_digit(7895, 1) == false
has_digit(7895, 8) == true
has_digit(7895, 5) == true
has_digit(7895, 0) == false
has_digit(7000, 0) == true
then:
bool matches_digit(int a, int b, int order)
with test cases:
matches_digit(1239, 4269, 0) == true
matches_digit(1239, 4269, 1) == false
matches_digit(1239, 4269, 2) == true
matches_digit(1239, 4269, 2) == false
and finally:
int get_cow(int a, int b)
int get_bull(int a, int b)
int main()
This is a top-down design, bottom-up implementation approach. First you think of the big picture and figure out what small pieces you need (functions) and then start implementing from the smallest most independent functions and step by step combine then into higher functions until you reach main.
This is my solution and it works. Basically I had to create a function to extract each digit and store them into a vector that can be applied to both the model and the guess. Then I used the find() method of the <algorithm> library to see if the digits exist in the guess vector and if yes, at which position compared to the model vector. Same position equals 1 bull and different position equals 1 cow. I am going to add more to this program, such as generating the model randomly and looping the program after each round so the user doesn't have to restart the game.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> getDigits(int modelValue) {
vector<int> vectorValue;
int extractedDigit = 0;
int modulant = 10000;
int divisor = 1000;
for (int i = 0; i < 4; i++) {
extractedDigit = (modelValue % modulant) / divisor;
vectorValue.push_back(extractedDigit);
modulant /= 10;
divisor /= 10;
}return vectorValue;
}
int main() {
int model = 1234;
int guess = 0000;
int bulls = 0;
int cows = 0;
int counter = 1;
cout << "Enter a value to guess: ";
cin >> guess;
vector<int> modelVector = getDigits(model);
vector<int> guessVector = getDigits(guess);
for (int i = 0; i < 4; i++) {
if (find(modelVector.begin(), modelVector.end(), guessVector[i]) != modelVector.end()) {
if (modelVector[i] == guessVector[i]) {bulls += 1;}
else { cows += 1; }
}
}cout << "There are " << bulls << " bulls and " << cows << " cows"<< endl;
}