GCD recursion function RTE in some IDEs - c++

Trying to implement gcd int function using Euclidean Algorithm with recursion. Results from CodeBlocks differ from IDEone (which I use to test my code before submitting to a CP website, TLX: https://tlx.toki.id, which I assume has similar compilers etc. because a lot of times IDEone and TLX got RTE while in CodeBlocks it ran without any problem). First Question: 1. Do they actually have something different that affects the output?
My first attempt was as follows:
#include <iostream>
#include <cmath>
using namespace std;
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <stdio.h>
#define pass (void)0
#include <cstdio>
#include <cstring>
#define ll long long
int gcd(int x, int y){
if(y!=0){
gcd(y, x%y);
//return x%y;
} else {
return x;
}
}
int main() {
cout << "test" << endl;
int z = gcd(100, 10);
cout << z << " bruh" << endl;
cout << "hello" << endl;
}
which IDEone spits out
Runtime error #stdin #stdout 0.01s 5380KB
test
while it ran as expected (z = 1 and prints out the correct stuff) in CodeBlocks
I tried to pinpoint where the error exactly occurs by 1. printing out at what part of the code my computer went error by the following way
void gcd(int x, int y){
if(y!=0){
cout << "if " << x << ", " << y << endl;
gcd(y, x%y);
} else {
cout << "else " << x << ", " << y << endl;
//return x;
}
}
int main() {
cout << "test" << endl;
//int z = gcd(100, 10);
gcd(100, 10);
//cout << z << " bruh" << endl;
cout << "hello" << endl;
}
which in both IDE, it outputted:
test
if 100, 10
else 10, 0
hello
then I also tried:
int gcd(int x, int y){
if(y!=0){
gcd(y, x%y);
//return x%y;
} else {
return x;
}
}
int main() {
cout << "test" << endl;
int z = gcd(100, 10);
cout << z << " bruh" << endl;
cout << "hello" << endl;
}
CodeBlocks outputted the first, while IDEone had an error as in the second
test
10 bruh
hello
Runtime error #stdin #stdout 0.01s 5380KB
test
from what I've tried and understand so far, it seems there's an error when the function gcd() calls the gcd() function. 2. Is my assumption correct? 3. and how am I supposed to solve this problem?
Thanks in advance

The problem is that the recursive case of the gcd() function does not run a return statement. Thus, it should be modified like this:
int gcd(int x, int y){
if(y!=0){
return gcd(y, x%y);
} else {
return x;
}
}
This could easily have been caught by enabling and reading compiler warnings.

Related

setprecision is not working the way I'm expecting (c++)

I keep receiving "10", when it should be "10.5" with the setprecision(1). I don't understand why it's happening and wish for some help rn! Thanks! I also linked the error message...
#include <iostream>
#include <iomanip>
using namespace std;
int avg(int a, int b)
{
int x = (a+b) / 2.0;
return x;
}
int main()
{
cout << fixed << setprecision(1) << avg(8, 13) << endl;
return 0;
}
spot_the_error_b.cpp: In function 'int main()':
spot_the_error_b.cpp:14:13: error: 'setPrecision' was not declared in this scope
14 | cout << setPrecision(1) << avg(8, 13) << endl;
|
You are returning an int in the avg function, you should return a double so that setprecision(1) can work correctly.
double avg(int a, int b)
{
return (a+b) / 2.0;
}

Getting method is undefined in C++

I'm trying to create a program from a C++ tutorial. But the IDE the tutor is using is VS2010 and I'm using VS2017. I noticed some of the syntaxes(sp.) are slightly different. I'm not sure what this error is and I've tried searching.
Here's the main .cpp:
#include "stdafx.h"
#include <iostream>
#include "Utility.h"
using namespace std;
int main()
{
int x;
cout << "Enter a Number: " << endl;
cin >> x;
if (IsPrime(x))
cout << x << " is prime" << endl;
else
cout << x << " is not prime" << endl;
if (Is2MorePrime(x))
cout << x << "+2 is prime" << endl;
else
cout << x << "+2 is not prime" << endl;
return 0;
}
The methods being tested out in the if conditions are both returning a "included method: identifier not found" and "included method: identifier is undefined"
Here's the included class .cpp:
#include "stdafx.h"
#include "Utility.h"
#include <iostream>
using namespace std;
bool Utility::IsPrime(int num)
{
bool prime = true;
for (int i = 0; i <= num / i; i++)
{
int factor = num / i;
if (factor*i == num)
{
cout << "Factor Found: " << factor << endl;
prime = false;
break;
}
}
return prime;
}
bool Utility::Is2MorePrime(int num)
{
num += 2;
return IsPrime(num);
}
And here's the included header file:
#pragma once
class Utility
{
bool IsPrime(int primeNum);
bool Is2MorePrime(int morePrime);
};
I'm still new to C++ programming so I don't know anything intensive yet.
The methods are in the Utility class yet you are calling them from main with no instance of Utility so the compiler/linker is looking for methods that don't exist.
You could probably make them static members of Utility and then you just need to scope the calls (e.g. Utility::IsPrime(x)) and not actually have an instance of Utility.
As mentioned by #Amadeus in the comments: If everything in Utility is "stateless" and can be static, then perhaps you should be putting all the Utility methods in a namespace instead of a class.

without declaration the function first, I can swap the value of the variables?

#include <iostream>
using namespace std;
void swap(int, int);
int main()
{
int a=10;
int b=20;
swap (a, b);
cout << "a: " << a << endl;
cout << "b: " << b << endl;
return 0;
}
void swap(int x, int y)
{
int t;
t = x;
x = y;
y = t;
}
those code above can't swap the value of a and b.
but my question is , when I forgot to type the third line "void swap(int, int);
" , the values of a and b swaped !! why?
It's because you have
using namespace std;
At the beginning of your source code.
This is a a bad programming practice, whose consequences you just experienced, first hand. You told the compiler that you want to invoke std::swap, without having any clue that you actually did that.
It's ironical, because you version of swap() won't work right, but std::swap does; so you were operating under the mistaken impression that your code was working, when it didn't.
Never use "using namespace std;" with your code. Simply forget that this part of the C++ language ever existed.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
cout << "a: " << a << endl;
cout << "b: " << b << endl;
system("pause");
swap(a, b);
cout << "a: " << a << endl;
cout << "b: " << b << endl;
system("pause");
return 0;
}
void swap is unnecessary
If you put the function definition above main then you don't need a prototype otherwise you do need it and the compiler should give you an error if you don't have a prototype

Error in self written code for factorial of a number in c++

Please point out the error in below code :
#include
using namespace std;
int factorial(int n) {
int f=1;
factorial(0)=1;
factorial(1)=1;
while(n>=0)
{
f=f*factorial(n);
n=n-1;
}
return f;
}
int main() {
cout << factorial(5);
}
In the compiler, I am getting the error "lvalue required as left operand of the assignment factorial(0)=1;"
I am unable to understand the above error. Please explain.
Your code is really wrong. You cannot assign a function to a value. I guess you're looking for something like this:
#include <iostream>
using namespace std;
int Factorial(int n)
{
if (n <= 1)
return 1;
return n * Factorial(n - 1);
}
int main()
{
int number = Factorial(5);
cout << number << endl;
}
C++ does not allow for pattern-matching function definitions.
Update: This one's like school on Saturday...
#include <iostream>
#include <unordered_map>
int& factorial(int n) {
static std::unordered_map<int,int> memo = {{0,1},{1,1}};
if(!memo.count(n)) {
memo[n] = n * factorial(n-1);
}
return memo[n];
}
int main() {
using std::cout;
cout << factorial(1) << '\n';
cout << factorial(5) << '\n';
cout << " ----\n";
factorial(1) = 123456789; // make factorial(1) better
cout << factorial(1) << '\n';
cout << factorial(5) << '\n'; // factorial(5) is still 120
// because its value was saved
// by the first factorial(5) call
}
It behaves like the original example, but the memoized results for factorial(0) and factorial(1) had to be added with an init list, unfortunately. Starting off with factorial(0) = 1; would have caused infinite recursion. When called with a value n, this version also automatically adds any missing factorial values to its memo, for all positive integers <= n. Best of all, the user can still customize the memoized result for any input like this: factorial(5) = 0;
Here's an example that uses classes and junk.
#include <iostream>
#include <unordered_map>
class factorial {
static std::unordered_map<int,int>& map() {
static std::unordered_map<int,int> outs;
return outs;
}
int n;
public:
factorial(int n) : n(n) {}
factorial& operator = (int out) {
map()[n] = out;
return *this;
}
operator int () const {
if(map().count(n)) return map()[n];
return factorial(n-1) * n;
}
};
int main() {
using std::cout;
// need to set low factorial values
// to prevent infinite recursion
factorial(0) = 1;
factorial(1) = 1;
cout << factorial(1) << '\n';
cout << factorial(5) << '\n';
cout << " ----\n";
factorial(1) = 123456789; // make factorial(1) better
cout << factorial(1) << '\n';
cout << factorial(5) << '\n'; // now factorial(5) is all messed up
cout << " ----\n";
factorial(5) = 120; // fix factorial(5)
cout << factorial(5) << '\n'; // worked!
}
Output:
1
120
----
123456789
1929912792
----
120
Live Demo

C++ Recursive functions

I'm learning C++ and I have trouble with getting recursion working when a function is called by itself.
#include <iostream>
using namespace std;
int countdown(int y) {
if (y==1) {
return 1 && cout << y << endl;
}
else {
return countdown(y-1);
}
}
int main () {
cout << "Countdown from ten: " << endl;
cout << countdown(10) << endl;
}
Of course there are other ways to achieve this, but really I created this example to verify my own understanding of how functions are called recursively.
In the example I added && cout << y to verify if y is being passed to the function as 1, which always appears to be the case irrespective that I call the function as countdown(10).
Could someone tell me if I'm missing something obvious here please?
Your ' cout << y ' only executes if y has been tested to be one.
This version does what I think you want:
#include <iostream>
using namespace std;
int countdown(int y)
{
cout << y << endl;
if (y==1)
{
return 1;
}
else
{
return countdown(y-1);
}
}
int main()
{
cout << "Countdown from ten: " << endl;
cout << countdown(10) << endl;
}
Your call stack looks like this:
main
countdown(10)
countdown(9)
countdown(8)
countdown(7)
countdown(6)
countdown(5)
countdown(4)
countdown(3)
countdown(2)
countdown(1)
std::cout << 1 << std::endl;
If you want to see the whole countdown, move the output command in front of the if condition.
Also, your style of writing the output is very unidiomatic. Note that it only works because 1 %&& cout converts the cout to bool and bool can be converted to int. Please don't write code like that.