Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Prints specific sequence by given n. For example n=1: 1, n=2: 121, n=3,1213121, n=4: 121312141213121 and so on. But for n > 11 the program stops working after 3556 cout. I think the problem is too many cout or too many recursive calls, but im not sure how to fix it or even is that really the problem. Please let me know if u have any solutions. Thank you so much!
#include <iostream>
using namespace std;
int findNumberByIndex(int index, int& number, int n) {
if (index < 0) {
return 0;
}
if (index % 2 == 0) {
return 1;
}
if (index == ((int)pow(2, number - 1) - 1)) {
return number;
}
index -= (int)pow(2, number);
findNumberByIndex(index, number, n);
}
int printSeq(int rowLen, int& index, int& number, int n, int& counter) {
if (index == rowLen) {
return 0;
}
int result = findNumberByIndex(index, number, n);
if (result == 0) {
number++;
}
else {
cout << result;
index++;
number = 2;
}
printSeq(rowLen, index, number, n, ++counter);
}
int main()
{
int n, index = 0, number = 2, seqLen = 1;
cin >> n;
int counter = 0;
if (n < 0 || n >= 20) {
return 0;
}
int rowLen = ((int)pow(2, n - 1) + (int)pow(2, n - 1) - 1);
printSeq(rowLen, index, number, n, counter);
cout << endl;
return 0;
}
In the definition of findNumberByIndex, you forgot to
return findNumberByIndex(index, number, n);
In the definition of printSeq, you forgot to
return printSeq(rowLen, index, number, n, ++counter);
This leads to undefined behaviour.
Regarding your hypothesis
I think the problem is too many cout or too many recursive calls
Unless specific concerns you can revoke the idea of "too many output". You could suffer from a too deep recursive call tree, but in your specific example your functions are tail-recusrive. With optimization correctly turned on, any decent compiler should optimize them.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed last month.
Improve this question
I need to find the largest sequence of identical digits in a given integer using a recursive function.
For example:
input: "2221", output: 3
input: "2223333", output: 4
input: "222333", output: 3
For some reason the code sometimes works correctly and sometimes it doesn't. when I input "1112" then it gives me the correct output (3), but when I input "1111555", I expected to get the output 4, but instead got 6.
Also, I can't change the parameters that the function receives so if someone knows how can I insert the parameters inside the function instead of outside (if I insert them inside the function then the output I receive is always 0)
I'd really appreciate the help so thank you in advance :)
My code:
int currentLength = 0, maxLength = 0;
int currentDigit = -1;
int maxSequence(int num)
{
if (num <= 0)
return maxLength;
int digit = num % 10;
if (digit == currentDigit) {
maxLength= 1 + maxSequence(num / 10);
}
else {
currentDigit = digit;
if (maxLength > 1)
{
maxLength = 0;
}
else
{
maxLength = 1;
}
return maxSequence(num / 10);
}
}
Recursion and mutable global variables is a nasty combination.
You can add the parameters to a different function and call that instead.
Something like this:
// Since you can't use std::max.
int max(int a, int b) { return a > b ? a : b; }
int maxSequenceHelper(int number, int last, int length, int maximum)
{
int digit = number % 10;
if (digit == last)
{
length += 1;
maximum = max(length, maximum);
}
else
{
length = 1;
}
return number < 10
? maximum
: maxSequenceHelper(number / 10, digit, length, maximum);
}
int maxSequence(int number)
{
return maxSequenceHelper(number / 10, number % 10, 1, 1);
}
And here is a version without any assignments, making it slightly easier to reason about:
int maxSequenceHelper(int number, int last, int length, int maximum)
{
const int digit = number % 10;
const int new_length = digit == last ? length + 1 : 1;
const int new_maximum = max(new_length, maximum);
return number < 10
? new_maximum
: maxSequenceHelper(number / 10, digit, new_length, new_maximum);
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I've written a code to find the largest prime factor that has, so far, worked for every single case that i've tested for, yet it fails when I input 600851475143. It keeps giving me 5102831 which is incorrect. I'm not sure why this happens even though I've checked it, help would be appreciated.
#include <iostream>
long int get_largest_prime_factor(long int);
int main()
{
std::cout << get_largest_prime_factor(600851475143);
return 0;
}
long int get_largest_prime_factor(long int prime_Number)
{
for(long int r = prime_Number - 1; r != 1; r--)
{
if(prime_Number % r == 0)
{
long int a = get_largest_prime_factor(r);
long int b = get_largest_prime_factor(prime_Number / r);
if(a == b)
return a;
return a > b? a : b;
}
}
return prime_Number;
}
Use this easy algorithm to get the right prime factor:
long long int getMaxPrimeFactor(long long int n) {
int i, max = -1;
while (n % 2 == 0) {
max = 2;
n /= 2;
}
for (i = 3; i <= sqrt(n); i = i + 2)
while (n % i == 0) {
max = i;
n /= i;
}
max = (n > 2) ? n : max;
return max;
}
This should output you:
6857
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is a problem on codeforces
and I have submitted a solution and I got TLE.
How to remove TLE
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
unsigned int y, k, n;
set <int> s;
cin >> y >> k >> n;
if (y >= n)
{
cout << -1; return 0;
}
for (int i = y + 1; i <= n; i++)
{
if (i%k == 0)
{
s.insert(i - y);
}
}
if (s.begin() == s.end())
{
cout << -1; return 0;
}
for (auto x : a)
cout << x << " ";
}
The problem seems at the algorithmic level. Instead to generate all candidate i values and then test if they are divisible by k, you can directly generate these values in a loop with an increment equal to k.
The minimum value iminis equal to k*((y+1)/k) or k*((y+1)/k) + k, depending if y+1 is divisible by kor not.
You have two gains: you consider k less candidates, and you avoid the costly % operation.
Moreover, when you find a value, you can directly print it, no need to memorize it.
Edit: here is the code
#include <iostream>
int main()
{
std::ios::sync_with_stdio(false);
unsigned int y, k, n;
std::cin >> y >> k >> n;
unsigned int imin = k*((y+1)/k);
if (imin < y+1) imin += k;
if (imin > n) {
std::cout << -1;
return 0;
}
for (unsigned int i = imin; i <= n; i+=k)
{
std::cout << i-y << " ";
}
return 0;
}
Edit 2: the last i-y calculation can be avoided by changing the bounds of the loop
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I want to print Fibonacci series from 1 to n in my function.
I know that I can do it by writing a regular Fibonacci and using it in a for block to print 1 to N. Like this:
#include <iostream>
using namespace std;
int fibo(int);
int main(){
for (int i = 0; i < 5; i++)
cout << fibo(5);
system("pause");
return 0;
}
int fibo(int n){
if (n == 1 || n == 2)
return 1;
else
return fibo(n - 1) + fibo(n - 2);
}
but my problme is that I can't do it without for,IN my function
I mean I want to Print it with a recursive algorithm
Here is my code up to now
#include <iostream>
using namespace std;
int fibo(int, bool);
int main(){
fibo(5, false);
system("pause");
return 0;
}
int fibo(int n, bool IsPrinted){
if (n == 1 || n == 2){
if (!IsPrinted)
cout << 1 << endl;
return 1;
}
else{
int temp = fibo(n - 1, IsPrinted) + fibo(n - 2, IsPrinted);
if (!IsPrinted){
cout << temp << endl;
IsPrinted = true;
}
return temp;
}
}
long fibo(int N, bool print) {
long value = 0;
if(1 == N)
value = 1;
if(1 < N)
value = fibo(N-1, print) + fibo(N-2, false);
if(print)
std::cout << N << " => " << value << std::endl;
return value;
}
int main(){
fibo(5, true);
return 0;
}
What you should realize is that the calls to the fibo function makes a tree. The root of the tree is the call to fibo(5, true) in the main(). As you only want to print each value once, the solution is to decide to print the value of the function only on the leftmost branch of that tree. The rule is then simply:
never print when on a right branch (hence the call to fibo(N-2, false)
never print if the parent didn't print (to avoid printing when on a child left branch of a right branch)
A common solution is to use memoization:
int fibo(int n)
{
static std::map<int,int> memo;
auto it=memo.find(n);
if(it!=std::end(memo))
{
return it->second;
}
int ret=1;
if (n > 2)
{
ret = fibo(n - 1) + fibo(n - 2);
}
memo[n]=ret;
return ret;
}
Then you can safely loop over the input parameters without recomputing the values over and over again:
for(int i=0;i<20;++i)
{
std::cout<<i<<" "<<fibo(i)<<std::endl;
}
Note that this is not only advantageous in printing but also for the calculation itself (at least as long as you call the function more than once).
Beside the above, you should also consider using long or double for the return type, as int will overflow more quickly.
EDIT: Ok, after your edit I don't know whether my answer exactly fits to your question, but I think it's a good advice anyway.
But here is another quick alternative which comes close, I guess:
int fibo(int n, bool first=true)
{
int ret=0;
if(n>2)
{
ret=fibo(n-1,false)+fibo(n-2,false);
}
else
{
ret=1;
}
if(first)
{
std::cout<<ret<<std::endl;
}
return ret;
}
DEMO
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have to make this C++ code in Dart, but I find it really difficult. I tryed watching Darts video and searching on the web, but with no success.Could someone be able to give me a hand?
This is the code:
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
if (n < 0) return 1;
int sum = 0;
int i = 0;
while (i <= n) sum += i*i;
cout << sum;
return 0;
}
something like
library x;
import 'dart:io';
void main(List<String> args) {
int n;
print('input a number');
String input = stdin.readLineSync();
n = int.parse(input);
print('n: $n');
if(n < 0) {
exit(1);
}
int sum = 0;
int i = 0;
while(i <= n) {
print(sum);
sum += i * i;
}
print(sum);
}
But don't expect to much.
When reaching the while loop sum and i are 0.
This way you have produced a nice endless loop to busy your computer ;-)
You could do the calculation bit (sum of squares of all numbers from 1 to n inclusive) with a recursive function like:
int recur(int n) => (n > 0) ? (n * n) + recur(n - 1) : 0;
Then it's a simple matter of figuring out how to enter n and output recur(n). That can be done with stdin.readLineSync and print. That would be along the following lines:
int recur(int n) => (n > 0) ? (n * n) + recur(n - 1) : 0;
void main( List<String> args ) {
int inNum;
String input = stdin.readLineSync();
inNum = int.parse( input );
if (inNum < 0) {
exit( 1 );
}
print( recur( sum ) );
}
Just be careful with large input values, I'm not sure whether Dart is smart enough to do tail end recursion optimisation. If not, stack space may be an issue.