Illegal instruction in while loop c++ - c++

I've been assigned to write a program that simplifies a rational number. What I want to do is compute the gcd and then divide the numbers by gcd. But the program returns a very strange error.
The code:
void read_rational(int& num, int& den) {
char bar;
if (cin >> num >> bar >> den) {
cout << "hi";
int a = num;
int b = den;
while (b != 0) {
int r = a%b;
a = b;
b = r;
}
num /= b;
den /= b;
}
}
INPUT: 10/2 OUTPUT: Illegal instruction (core dumped)
INPUT: 90/8 OUTPUT: Illegal instruction (core dumped)
I've tried commenting out some bits of the script. The program seems to crash only when the while loop is present. But I can't see what's wrong with it.

Indeed, the issue is the while loop. After it finishes, b is actually 0, so the divisions after raise these errors.
I think what you want is a instead of b.

Related

How to do a pow function inside of while? C++

Here is the problem I must do(Just for context): Write a program that will input 2 integers from the user, will then calculate the first to the power of the second and then output the result. The Input, calculation and output should be in three separate subprograms/functions. You must calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times. For this homework only, you are allowed to use global variables to move information between functions.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
double a, b, ans;
int main()
{
cout << "Please enter two whole numbers: ";
cin >> a >> b;
cout << conclusion() << calc();
system("pause");
return 0;
}
int calc()
{
double ans = pow(a, b);
return 0;
}
int conclusion()
{
cout << a << " To the power of " << b
<< " is " << ans;
return 0;
}
So here's what I'm having an issue with, I do online classes. The dude is like, "here's a problem, figure it out and just do it." Which is fine I guess, but when things like this come up its hard to find certain tutorials and questions. Anyway, I got my BASE code down. Now I need a while loop, and have no idea what this means: calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times.
I figured I could just do a while and do
double ans = pow(a, b);
But that's not the case apparently. That's what my chapter taught me, but not with a while and all this extra stuff you need to do for this. I asked a classmate, she said she had a really difficult time as well, and her example to me was:
int a = 0;
int b = 0;
int c = 1;
cin >> a;
cin >> b;
int powerOp(int a, int b, int c)
{
while (b > 0)
{
c = c * a;
b--;
}
cout << c;
return c;
}
I have been working almost all day and can't figure this out. I don't understand why we need to factorize and set the int = 1. I thought it could simply be
double ans = pow(a, b); //a and b being the 2 numbers the user inputs
Its pretty simple, lets say you have 2^3. You and I both agree that it is the same as doing 2x2x2. You mutiplied you first number A by itself B (your second number) times. Now for your loop, what you want have your second number server as your counter AND loop exit condition. Something like this
double YourPowerFunction(int a, int b)
{
int counter = 0;
double result = 1;
while (counter < b)
{
counter++:
result = result * a;
}
return result;
}
Okay so I'm pretty sure I found the answer. Result is the variable for ans
int calc() //function for calculation
{
//Still not sure how I did this one, after hours of playing around with it
while (b > 0) //This code is adding a 0 in the result. I can't figure it out
{
result = result * a;
b--;
}
return (result);
}
This is just a simple solution, as it wants to add a 0 in the end result.

Why does my code for SPOJ GCD2 error on SPOJ?

Following is code for SPOJ GCD2. It's running well on my machine and Ideone, but getting runtime error (SIGFPE) on SPOJ. I have checked all the test cases also available at spojtoolkit.com.
I am unable to figure out why this code is showing runtime error (SIGFPE) on spoj. SIGFPE means Erroneous arithmetic operation.
Why is this code showing runtime error on SPOJ?
#include <bits/stdc++.h>
using namespace std;
int gcd(int x,int a)
{
if(a==0)
return x;
else
return gcd(a, x%a);
}
int getmod(string b,int a)
{
int n=b.size();
int d;
d= (b[0]-'0') % a;
for(int i=1; i!=n; i++)
{
d=d*10;
d=d + (b[i]-'0');
d= d % a;
}
return d;
}
int main()
{
int tc;
cin >> tc;
int a;
string b;
while(tc--)
{
cin >>a>>b;
int x=getmod(b,a);
cout << gcd(x,a)<<endl;
}
return 0;
}
int getmod(string b,int a)
{
int n=b.size();
int d;
d= (b[0]-'0') % a;
If a = 0, this will error, because % 0 is like dividing by zero. a can be zero according to the problem statement.
The error covers division by zero:
The SIGFPE signal reports a fatal arithmetic error. Although the name is derived from “floating-point exception”, this signal actually covers all arithmetic errors, including division by zero and overflow. If a program stores integer data in a location which is then used in a floating-point operation, this often causes an “invalid operation” exception, because the processor cannot recognize the data as a floating-point number.
You can fix it by checking if a == 0 and simply returning b as the answer in that case. Else call your current function as is.

Calculate power with a recursive function on C++

I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
Instead of b-- you need b-1 (or --b)
b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.
Also, when b is zero, the result should be 1 rather than a
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
Stopping criteria
X ^ 0 = 1
Unwinding the stack
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
If A is the base and B the power, as a first step, take the absolute
value of B.
Secondly, store A in the stack and decrement B. Repeat
until B = 0 (stopping criterion). Store the result in the stack.
Thirdly, multiply all the A's stored by unwinding the stack.
Now the code
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}

Keep getting 1.#INF as my output

#include <iostream>
using namespace std;
double calc(int a, int b);
int main()
{
int n1, n2;
cout << "Enter a number for a: ";
cin >> n1;
cout << "Enter a number for b: ";
cin >> n2;
cout << calc(n1, n2) << endl;
system("PAUSE");
return 0;
}
double calc(int a, int b)
{
double s;
s = (a) / ((sqrt(a / b)));
return s;
}
This program is meant to check whether the two integers are greater than zero. If it is it will calcualte the formula. Otherwise if one of the integers is zero or less than zero it will not return anything and exit the program.
My question here is that no matter what I input for a and b, i keep getting 1.#INF as the output and I have no idea why. I've checked the formula in a seperate program and it worked fine.
Any ideas?
Here, you are operating with int numbers:
s = (a) / ((sqrt(a / b)));
If a is less then b, then a/b (both are integers, remember, so the fractional part of the result will simply be lost) will be equal to 0, which leads to division by 0. You need to cast one of the numbers to double:
s = (a) / ((sqrt(static_cast<double>(a) / b)));
sqrt takes and returns a double. When you call it with integer arguments it will be converted in a double, and will thus get the value of infinity.
change your function signature to:
double calc(double a, double b);
and declare n1 and n2 as double.
You say that the function will exit the program when one of the integers are 0 or less, but where?
Try to check them like this:
Additionally, you should have a check whether a is greater than b
double calc(int a, int b)
{
double s;
if(a <= 0) exit(-1);
if(b <= 0) exit(-1);
if(a < b) exit(-1);
s = (a) / ((sqrt(a / b)));
return s;
}
You are having problems with infinity. For it use isinf. Here is some sample usage:
#include <stdio.h> /* printf */
#include <math.h> /* isinf, sqrt */
int main()
{
printf ("isinf(-1.0/0.0) : %d\n",isinf(-1.0/0.0));
printf ("isinf(sqrt(-1.0)): %d\n",isinf(sqrt(-1.0)));
return 0;
}
output:
isinf(-1.0/0.0) : 1 isinf(sqrt(-1.0): 0

Program crashes when inputs are high values

My code works when the values are small e.g. [a = 1, gos = 0.5, N = 1] & [a = 1, gos = 0.2 , N = 2].
However, it crashes when bigger values are entered. e.g.[a = 10, gos = 0.01, N = 18] & [a=50, gos=0.01, N=64].
How can I fix it?
Here's the code:
#include <cstdlib>
#include <iostream>
using namespace std;
double num_trunks(double A, double B, int N);
double num_trunk_checker(double B, double gos, int N, double A);
double num_trunks(double A, double B, int N)
{
double gos_prev = 1;
double gos;
int k = 1;
while (k != (N+1))
{
gos = (A*gos_prev)/(k+(gos_prev)*A);
gos_prev = gos;
k++;
};
num_trunk_checker(B,gos,N,A);
}
double num_trunk_checker(double B, double gos, int N, double A)
{
if (B != gos)
{
N = N + 1;
num_trunks(A,B,N);
}
else
{
cout << "Number of trunks: " << N << "\n";
}
}
int main(int argc, char *argv[])
{
double A, gos;
int N = 1;
cout << "A: ";
cin >> A;
cout << "gos: ";
cin >> gos;
num_trunks(A,gos,N);
system("PAUSE");
return EXIT_SUCCESS;
}
In num_trunks(A, B, N), you calculate a gos value, and then call num_trunk_checker(B, gos, N, A). But in num_trunk_checker, if B does not match gos, you turn around and call num_trunks(A, B, N+1). So the only thing that changed is a larger N, and you get infinite recursion if gos never equals B.
num_trunks(A, B, N)
calculuate gos (which has to be less than 1)
num_trunk_checker(B, gos, N, A)
num_trunk_checker(B, gos, N, A)
if (B != gos) num_trunks(A, B, N+1)
It is possible for gos to step over the value of B, so you never get equality.
Perhaps what you meant was:
if (gos > B) //...
you should read the FAQ about floating point comparisons
http://www.parashift.com/c++-faq/floating-point-arith.html
then try sth like
if (fabs(B-gos)<1.e-6)
in num_trunk_checker function
Without more information (what crashes? How long does it take?) it is impossible to solve your problem perfectly. But some reasonable guesses can be made.
Floating point comparisons are not completely accurate and are usually done by subtracting the two values and comparing against a small value (called epsilon). It might be better, when checking (B != gos), to do something like (B - gos < .00001). Without this, the computation may not terminate; and if it did not, the recursion would continue indefinitely, until the stack overflowed and the program crashed.
Another possibility (I am not running the program to see what happens myself) is that with larger values, the multiplication causes them to overflow (to exceed the maximum possible value that can be represented in a double), causing an exception to be thrown.