debug horner's rule programme - c++

I am a beginner and totally confused.
I am getting two errors in my c++ code:
Program:32:5: error: redefinition of 'main'
Program:3:6: note: previous definition of 'main' was here
You are given a polynomial of degree n. The polynomial is of the form P(x) = anxn + an-1xn-1 + … + a0. For given values k and m, You are required to find P(k) at the end of the mth iteration of Horner’s rule. The steps involved in the Horner’s rule are given below,
Pn (x) = an
Pn-1 (x) = an-1 + x * Pn (x) 1st iteration.
Pn-2 (x) = an-2 + x * Pn-1 (x) 2nd iteration.
.
.
P0 (x) = a0 + x * P1 (x) nth iteration.
In general, Pi (x) = ai + x * Pi + 1 (x) and P0(x) is the final result. The input to your program is as follows,
Line 1 contains the integers n, m and k separated by space.
Line 2 contains the coefficients an, an-1…, a0 separated by space.
INPUT: Integers n, m, k and the coefficients as described above.
OUTPUT: P(k) value at the end of the mth iteration.
Sample Input:
2 2 5
3 2 1
Sample Output:
86
Constraints:
1 <= n, k, m <= 10
0 <= ai <=10
#include <stdio.h>
#include <string.h>
int main() {
int num, i, j, result, index;
char name[11][11];
char temp[11];
scanf("%d\n", &num);
for(i = 0; i < num; i++)
scanf("%s\n", name[i]);
for(i = 0; i < num; i++) {
index = i;
for(j = i + 1; j < num; j++) {
result = strcmp(name[index], name[j]);
if(result > 0)
index = j;
}
strcpy(temp, name[index]);
strcpy(name[index], name[i]);
strcpy(name[i], temp);
}
for(i = 0; i < num-1; i++) {
printf("%s", name[i]);
printf("\n");
}
printf("%s", name[num-1]);
return 0;
}
#include<stdio.h>
int horner(int [], int, int);
int main()
{
int n, m, k, i;
int a[10];
scanf("%d%d%d",&n,&m,&k);
for (i=0; i<=n; ++i){
scanf("%d",&a[i]);
}
printf("%d",horner(a,m,k));
return 0;
}
int horner(int a[], int m, int k){
if (m==0){
return a[m];
}
else{
return a[m] + k * horner(a,m-1,k);
}
}

The error message seems to have nailed the problem quite well. You've got two main functions. You can only have one, so pick one and delete the other.

Program:32:5: error: redefinition of 'main'
In "Program", line 32, column 5, the identifier main is defined a second time in the same scope.
Program:3:6: note: previous definition of 'main' was here
The first definition was in "Program", line 3, column 6.
There you are. You cannot define the same function twice. There really is nothing to add.
Except perhaps:
Use consistent indentation. Always four spaces is a good rule. Avoid tabulators if you can, they are asking for trouble.
Always put {} around the blocks of if, for, and while, even if they are only one line. Personally, I even add them if the block is empty, adding a // EMPTY comment to make it explicit that the emptiness is not due to a simple typing error.
Whitespace is free. It does not slow down your typing much, and it does make reading the source much easier. You read source much more often than typing it, so do yourself that favor.
Then there's Debugging 101:
Cut away some source that doesn't look as if it's contributing to your problem (which, in this case, is "redefinition of 'main'", not Horner's Rule).
Check if the problem persists.
Cut away MORE source, until you find the ONE change that makes your error go away. Either the problem is now evident to you, or you have found a minimal example to post on something like StackOverflow.
You could have cut away basically everything and end up with:
int main()
{
return 0;
}
int main()
{
return 0;
}
Hmm... what seems to be the problem? Maybe I re-defined 'main()'? ;-)

Related

C++ Largest number in array. Positive and negative

I have a task to print maximum int of matrix second line.
Example input:
3 2 (n, m)
-1 -2 <- 1 line
4 5 <- 2 line
2 6 <- 3 line
Max int in second line is 5. My program prints it. But if second line would be -100 -150, it not works. Sure it is because I have max = 0, but I don't know how to use it properly. I'm a student. Thanks in advance.
It is my code:
#include <iostream>
using namespace std;
int main() {
int n, m, max = 0;
cin >> n >> m;
int matrix[10][10];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (matrix[1][j] > max) {
max = matrix[1][j];
}
}
}
if (max == 0 || n == 1) {
cout << "No";
} else {
cout << max;
}
}
And code works pretty good, unless there are negative numbers in second line
You are correct to suspect max = 0;. Why is that a problem? Well, first, perhaps you should try to explain to your rubber duck why it is correct. As you try to do so, you are likely to express an intent along the lines of "this value will not make it through the checks" or "this value will be replaced in the first iteration of the loop". Why? "Because matrix[1][j] > max will be true, so... Hold on, wasn't the problem when matrix[1][j] > 0 is false? So when max is 0, um... problem?"
The overall strategy is valid, but there is a requirement that max be initialized to a low enough value. There are two common strategies I can think of at the moment.
Use a value that is as low as possible for the type you are using. That is:
int max = std::numeric_limits<int>::lowest();
Use the value from the first iteration of the loop. No need to provide a value that is just going to be replaced anyway. There are some caveats for this, though. The most relevant for your example can be expressed as a question: what if there is no first iteration? (Perhaps there is only one row? Perhaps there are no columns?) Also, you would need to initialize max between your loops, after the matrix has been given values.
int max = (n > 1 && m > 0) ? matrix[1][0] : /* what value do you want here? */;

SIGSEGV Error in Simple Dynamic Programming on SPOJ

I am just beginning with dynamic programming, and I have just attempted a simple question based on DP, on Spoj. Link - http://www.spoj.com/problems/MST1/
Here is the question statement -
On a positive integer, you can perform any one of the following 3
steps.
1.) Subtract 1 from it. ( n = n - 1 )
2.) If its divisible by 2, divide by 2. ( if n % 2 == 0 , then n = n / 2 )
3.) If its divisible by 3, divide by 3. ( if n % 3 == 0 , then n = n / 3 )
Given a positive integer n and you task is find the minimum number of
steps that takes n to one.
Input:
The input contains an integer T (1 ≤ T ≤ 100) number of test cases.
Second line input is N (0 < N ≤ 2*10^7 ) that indicates the positive
number.
Output:
For each case, print the case number and minimum steps.
Here's my code -
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
// Memo Function returns the smallest number of steps possible for integer a
int memo(int a, int mem[]);
int mem[20000010];
int main() {
int t;
scanf("%i", &t);
for(int i = 1; i <= t; i++) {
int n;
scanf("%i", &n);
memset(mem, -1, sizeof(mem));
mem[1] = 0;
printf("Case %i: %i\n", i, memo(n, mem));
}
return 0;
}
int memo(int a, int mem[]) {
if (mem[a] != -1) return mem[a]; // If the value of smallest steps have already been calculated
int r; // Current Lowest number of steps
r = memo(a - 1, mem) + 1;
if (a % 2 == 0) r = min(r, memo(a/2, mem) + 1);
if (a % 3 == 0) r = min(r, memo(a/3, mem) + 1);
mem[a] = r;
return r;
}
I have looked up this error on the internet and here on StackOverflow, and I have found that it may occur when we are trying to access the memory that has not been allocated, for example accessing the 11th element of a 10 element array. But I don't think that's the case here.
Also, I think the upper limit of the question is 2*10^7, also the array is global, so it shouldn't be an issue. Maybe there's some issue in the way I am using the memset function? I really don't know!
Any help will be appreciated! Thanks for reading!
Your DP idea is correct but your code is not working for a large inputs (e.g. 1x10^6, or the upper boundary, 2x10^7).
By changing your code a little, you can pre-compute every answer and then output only the ones you are interested in. It will be not very time-consuming because of the dynamic programming fashion of the problem, i.e., a complex problem can be solved as a combination of one or more previously solved problems.
int main()
{
// Initialize DP array
memset(mem, -1, sizeof(mem));
mem[1] = 0;
// Pre-compute every possible answer
for(int i = 2; i <= 20000000; i++)
mem[i] = memo(i);
// Read the number of test cases
int t;
scanf("%d", &t);
// Print only the desired answer, ie, mem[n]
for(int i = 1; i <= t; i++) {
int n;
scanf("%d", &n);
printf("Case %d: %d\n", i, mem[n]);
}
return 0;
}
I got an ACCEPTED with this approach.
Another tip: since your DP array is global, you do not have to pass it to the DP function every time.

run time error - non zero exception

my programming teacher gave me this problem to code it in c :
given array of N integers A and a number K. During a turn the maximal value over all Ai is chosen, let's call it MAX. Then Ai =
MAX - Ai is done for every 1 <= i <= N. Help Roman to find out how will the array look like after K turns.
Input
The numbers N and K are given in the first line of an input. Then N integers are given in the second line which denote the array A.
Output
Output N numbers on a single line. It should be the array A after K turns.
Constraints
* 1 <= N <= 10^5
* 0 <= K <= 10^9
* Ai does not exceed 2 * 10^9 by it's absolute value.
Example
Input:
4 1
5 -1 7 0
Output:
2 8 0 7
and my code to this problem is :
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
long int Max(long int *arr, int low, int high)
{
long int max,i;
max = arr[low];
for(i=0;i<=high;i++)
{
if(max<=arr[i])
max = arr[i];
}
return max;
}
/* Driver program to test above function */
int main()
{
long int max,*arr;
long int n,k,c1,c2,c3,i,j;
c1 = (long int)pow(10,5);
c2 = (long int)pow(10,9);
c3 = 2*c2;
scanf("%ld %ld",&n,&k);
if(n<1||n>c1)
exit(1);
else if(k<0||k>c2)
exit(1);
else
{
arr = (long int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
{
scanf("%ld",&arr[i]);
if(abs(arr[i])>c3)
exit(1);
}
if(k%2 == 0)
{
for(i=0;i<2;i++)
{
max = Max(arr, 0, n-1);
for(j=0;j<n;j++)
{
arr[j] = max-arr[j];
if(abs(arr[j])>c3)
exit(1);
}
}
}
else if(k%2 != 0)
{
max = Max(arr, 0, n-1);
for(j=0;j<n;j++)
{
arr[j] = max-arr[j];
/*if(abs(arr[j])>c3)
exit(1);*/
}
}
/* for(m=0;m<n;m++)
printf("%ld ",arr[m]);
printf("\n");*/
for(i=0;i<n;i++)
printf("%ld ",arr[i]);
printf("\n");
}
return 0;
}
i executed this code on gcc compiler in ubuntu, it is working perfectly with all the constraints satisfied but when I uploaded this code on my teacher's portal which has a compiler and executed the code, it said Runtime error -
nzec which means a non-zero exception which is used to signify that main() does not have "return 0;" statement or exception thrown by c++ compiler.
Please, can anyone help me what is wrong in my code as there is a return 0; statement in my code. Please Help.
Everyone has pointed out multiple use of exits ... Can I reduce them using any other way in place of exit()?
My guess is that it has to do with the various exit(1) statements you have for error conditions.
As pointed out by Dave Costa, exit(1) could be the cause
Another possible problem is the size of the allocated array:
arr = (long int *)malloc(sizeof(int)*n);
should be:
arr = malloc(sizeof(long int)*n);
And note that you don't need to use pow for constants:
c1 = (long int)pow(10,5);
c2 = (long int)pow(10,9);
could be replaced with:
c1 = 1e5L;
c2 = 1e9L;

Recursive function that takes the sum of odd integers

The program runs but it also spews out some other stuff and I am not too sure why. The very first output is correct but from there I am not sure what happens. Here is my code:
#include <iostream>
using namespace std;
const int MAX = 10;
int sum(int arrayNum[], int n)
{
int total = 0;
if (n <= 0)
return 0;
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0)
total += arrayNum[i];
}
cout << "Sum of odd integers in the array: " << total << endl;
return arrayNum[0] + sum(arrayNum+1,n-1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
sum(x,MAX);
system("pause");
return 0;
}
The term recursion means (in the simplest variation) solving a problem by reducing it to a simpler version of the same problem until becomes trivial. In your example...
To compute the num of the odd values in an array of n elements we have these cases:
the array is empty: the result is trivially 0
the first element is even: the result will be the sum of odd elements of the rest of the array
the first element is odd: the result will be this element added to the sum of odd elements of the rest of the array
In this problem the trivial case is computing the result for an empty array and the simpler version of the problem is working on a smaller array. It is important to understand that the simpler version must be "closer" to a trivial case for recursion to work.
Once the algorithm is clear translation to code is simple:
// Returns the sums of all odd numbers in
// the sequence of n elements pointed by p
int oddSum(int *p, int n) {
if (n == 0) {
// case 1
return 0;
} else if (p[0] % 2 == 0) {
// case 2
return oddSum(p + 1, n - 1);
} else {
// case 3
return p[0] + oddSum(p + 1, n - 1);
}
}
Recursion is a powerful tool to know and you should try to understand this example until it's 100% clear how it works. Try starting rewriting it from scratch (I'm not saying you should memorize it, just try rewriting it once you read and you think you understood the solution) and then try to solve small variations of this problem.
No amount of reading can compensate for writing code.
You are passing updated n to recursive function as argument but not using it inside.
change MAX to n in this statement
for(int i = 0; i < n; i ++)
so this doesnt really answer your question but it should help.
So, your code is not really recursive. If we run through your function
int total = 0; //Start a tally, good.
if (n <= 0)
return 0; //Check that we are not violating the array, good.
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0) //THIS PART IS WIERD
total += arrayNum[i];
}
And the reason it is wierd is because you are solving the problem right there. That for loop will run through the list and add all the odd numbers up anyway.
What you are doing by recursing could be to do this:
What is the sum of odd numbers in:
13,14,8,7,45,89,22,18,6,10
+
14,8,7,45,89,22,18,6
+
8,7,45,89,22,18
+
7,45,89,22 ... etc
And if so then you only need to change:
for(int i = 0; i < MAX; i ++)
to
for(int i = 0; i < n; i ++)
But otherwise you really need to rethink your approach to this problem.
It's not recursion if you use a loop.
It's also generally a good idea to separate computation and output.
int sum(int arrayNum[], int n)
{
if (n <= 0) // Base case: the sum of an empty array is 0.
return 0;
// Recursive case: If the first number is odd, add it to the sum of the rest of the array.
// Otherwise just return the sum of the rest of the array.
if(arrayNum[0] % 2 != 0)
return arrayNum[0] + sum(arrayNum + 1, n - 1);
else
return sum(arrayNum + 1, n - 1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
cout << sum(x,MAX);
}

What's wrong with this Pollard Rho implementation

#include <iostream>
#include <cstdlib>
typedef unsigned long long int ULL;
ULL gcd(ULL a, ULL b)
{
for(; b >0 ;)
{
ULL rem = a % b;
a = b;
b = rem;
}
return a;
}
void pollard_rho(ULL n)
{
ULL i = 0,y,k,d;
ULL *x = new ULL[2*n];
x[0] = rand() % n;
y = x[0];
k = 2;
while(1){
i = i+1;
std::cout << x[i-1];
x[i] = (x[i-1]*x[i-1]-1)%n;
d = gcd(abs(y - x[i]),n);
if(d!= 1 && d!=n)
std::cout <<d<<std::endl;
if(i+1==k){
y = x[i];
k = 2*k;
}
}
}
int main()
{
srand(time(NULL));
pollard_rho(10);
}
This implementation is derived from CLRS 2nd edition (Page number 894). while(1) looks suspicious to me. What should be the termination condition for the while loop?
I tried k<=n but that doesn't seem to work. I get segmentation fault. What is the flaw in the code and how to correct it?
I only have a 1st edition of CLRS, but assuming it's not too different from the 2nd ed., the answer to the termination condition is on the next page:
This procedure for finding a factor may seem somewhat mysterious at first. Note, however, that POLLARD-RHO never prints an incorrect answer; any number it prints is a nontrivial divisor of n. POLLARD-RHO may not print anything at all, though; there is no guarantee that it will produce any results. We shall see, however, that there is good reason to expect POLLARD-RHO to print a factor of p of n after approximately sqrt(p) iterations of the while loop. Thus, if n is composite, we can expect this procedure to discover enough divisors to factor n completely after approximately n1/4 update, since every prime factor p of n except possibly the largest one is less than sqrt(n).
So, technically speaking, the presentation in CLRS doesn't have a termination condition (that's probably why they call it a "heuristic" and "procedure" rather than an "algorithm") and there are no guarantees that it will ever actually produce anything useful. In practice, you'd likely want to put some iteration bound based on the expected n1/4 updates.
Why store all those intermediary values? You really don't need to put x and y in a array. Just use 2 variables which you keep reusing, x and y.
Also, replace while(1) with while(d == 1) and cut the loop before
if(d!= 1 && d!=n)
std::cout <<d<<std::endl;
if(i+1==k){
y = x[i];
k = 2*k;
So your loop should become
while(d == 1)
{
x = (x*x - 1) % n;
y = (y*y - 1) % n;
y = (y*y - 1) % n;
d = abs(gcd(y-x,n))%n;
}
if(d!=n)
std::cout <<d<<std::endl;
else
std::cout<<"Can't find result with this function \n";
Extra points if you pass the function used inside the loop as a parameter to pollard, so that if it can't find the result with one function, it tries another.
Try replacing while(1) { i = i + 1; with this:
for (i = 1; i < 2*n; ++i) {