process terminated with status -1073740940 - c++

background: I was writing a c++ program to solve this problem:
For a positive integer N, the digit-sum of N is defined as the sum of N itself and its digits. When M
is the digitsum of N, we call N a generator of M.For example, the digit-sum of 245 is 256 (= 245 + 2 + 4 + 5). Therefore, 245 is a generator of
256. Not surprisingly, some numbers do not have any generators and some numbers have more than one generator. For example, the generators of 216 are 198 and 207.
You are to write a program to find the smallest generator of the given integer.
Input
Your program is to read from standard input.
The input consists of T test cases.
The number of test cases T is given in the first line of the input.
Each test case takes one line containing an integer N, 1 ≤ N ≤ 100, 000.
Output
Your program is to write to standard output.
Print exactly one line for each test case.
The line is to contain a generator of N for each test case.
If N has multiple generators, print the smallest.
If N does not have any generators, print ‘0’.
my problem: the program below always terminated with status -1073740940, I wonder why and need some help
int main()
{
int* ans = new int[100005]();
int y;
int i_op;
for(int i = 1; i < 100001; ++i){
y = i;
i_op = i;
while(i_op){
y += i_op%10;
i_op /= 10;
}
if(ans[y] == 0 || i < ans[y]){
ans[y] = i;
}
}
int t;
int n;
cin >> t;
for(int i = 0; i < t; ++i){
cin >> n;
cout << ans[n] << endl;
}
//========================
//problem occurs here //after doing all output, the process terminated with status -1073740940
//========================
delete[] ans;
return 0;
}
input data: (both terminated with status -1073740940)
10
70587
38943
37061
95352
84205
96532
21150
26337
97804
65891
and
100000
1
2
……
100000

You may be writing past the end of your array during the computation and corrupting something. What happens for i = 99999? I don't think 100005 is quite enough to contain that. Let's check:
#include <stdio.h>
int main() {
int i = 99999;
int y = i;
int i_op = i;
while(i_op){
y += i_op%10;
i_op /= 10;
}
printf("%d\n", y);
}
Outputs 100044. Indeed.

Related

C++ Program to print sum of digits

//Program to print sum of digits
#include <iostream>
using namespace std;
int main()
{
int n, m, sum = 0;
cin >> n;
for(int i = 0; i < n; i++)
{
m = n % 10;
sum += m;
n = n / 10;
}
cout << sum;
}
//Outputs
// Input = 123
// Output = 5 (should be 6)
// Input = 0235
// Ouput = 8 (should be 9)
Not printing the right answer when input no. is starting from 1 or 0.
By using While (n>0), it's giving the right output but I can't figure out why?
For starters the user can enter a negative number because the type of the variable n is the signed type int.
Thus neither loop either
for(int i = 0; i < n; i++)
or
while (n>0)
will be correct.
A correct loop can look like
while ( n != 0 )
And you need to convert each obtained digit to a non-negative value or you should use an unsigned integer type for the variable n.
As for this loop
for(int i = 0; i < n; i++)
then it entirely does not make a sense.
For example let's assume that n is initially equal to 123,
In this case the in the first iteration of the loop the condition of the loop will look like
0 < 123
In the second iteration of the loop it will look like
1 < 12
And in the third iteration of the loop it will look like
2 < 1
That means that the third iteration of the loop will not be executed.
Thus as soon as the last digit of a number is less than or equal to the current value of the index i the loop stops its iterations and and the digit will not be processed.

How to debug my program that runs properly but returns segmentation fault in an ide?

using namespace std;
#include<iostream>
class biker
{
public:
int initspeed, acc, speeding;
};
void input(int n, biker a[])
{
for (int i = 0; i < n; i++)
{
//cout<<"Enter the initspeed:"<<"\n";
std::cin >> a[i].initspeed;
//cout<<"Enter the acceleration:"<<"\n";
std::cin >> a[i].acc;
}
}
int main()
{
int n = 0, i = 0, t = 0, max_speed = 0, flag = 0, minimum = 0;
biker a[100];
std::cin >> t;
for (int k = 0; k < t; k++)
{
//cout<<"Enter no of bikers"<<"\n";
std::cin >> n;
//cout<<"enter the max track speed"<<"\n";
std::cin >> max_speed;
//cout<<"Enter the min niker speed"<<"\n";
std::cin >> minimum;
input(n, a);
int j = 1, x = 0;
while (flag < 500)
{
int sum = 0;
for (i = 0; i < n; i++)
{
int prod = 0;
prod = a[i].acc * j;
x = a[i].initspeed + prod;
// cout<<"VAL"<<x<<"\n";
if (x >= minimum)
{
//cout<<"It is greater than minimum";
sum = sum + a[i].initspeed + prod;
//cout<<sum<<"\n";
}
}
if (sum >= max_speed)
{
//cout<<"MAXIMUM ACHIEVED\n";
x = sum;
break;
}
j++;
flag++;
}
//cout<<x<<"\n";
std::cout << j;
}
return 0;
}
The above code is my solution to the bike racing problem in geeksforgeeks.
Summary:
A Bike race is to be organized. There will be N bikers. You are given initial Speed of the ith Biker by Hi and the Acceleration of ith biker as Ai KiloMeters per Hour.
The organizers want the safety of the bikers and the viewers.They monitor the Total Speed on the racing track after every Hour.
A biker whose Speed is 'L' or more, is considered a Fast Biker.
To Calculate the Total speed on the track- They Add the speed of each Fast biker ,at that Hour.
As soon as The total speed on the track is 'M' KiloMeters per Hour or more, The safety Alarm buzzes.
You need to tell what is the minimum number of Hours after which the safety alarm will buzz.
Input:
The first Line contains T- denoting the number of test cases.
The first line of each test case contains three space-separated integers N, M and L denoting the number of bikers and speed limit of the track respectively, and A fast Biker's Minimum Speed.
Each of next N lines contains two space-separated integers denoting Hi and Ai respectively.
Output:
For each test case-Output a single integer denoting the minimum number of Hours after which alarm buzzes.
Constraints:
1<=T<=100
1<=N<=1e5
1 ≤ M,L ≤ 1e10
1 ≤ Hi, Ai ≤ 1e9
My code runs properly on my computer and also on the ide .But when i click submit, it crashes returning Segmentation fault(SIGSEGV).
The array a can contain at most 100 bikers. The problem statement specifies that the number of bikers can be up to 10,000.
Overrunning the end of the array invokes Undefined Behaviour (UB) which is manifesting as a segfault on the judging system. Either the UB is manifesting differently on your development system or you have not tested it with a sufficiently large number of bikers.

Armstrong numbers. print armstrong numbers

I kindly request those who think this question have been asked earlier, read on first.
I need to print all armstrong numbers between 1 and 10000. My problem is that whenever my program is run and reaches 150, it does
(1^3) + ((5^3)-1) + (0^3)
instead of
(1^3) + (5^3) + (0^3).
Thus it does not print 153 (which is an Armstrong number), of course because the sum results in 152. I do not know if some other numbers are also doing this. But i do have checked untill 200 and there is no problem with other numbers except that in 150–160 range.
Is this a compiler error. Should i re-install my compiler? Currently i am using codeblocks.
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
for(int i = 0;i <= 10000;++i)
{
int r = i;
int dig = 0;
while(r != 0)
{
dig++;
r /= 10;
}
int n = i, sum = 0;
while(n != 0)
{
int d = n % 10;
sum += pow(d, dig);
n /= 10;
}
if(sum == i)
cout << i << ' ';
}
cout << "\n\n\n";
return 0;
}
You should run your code in the debugger. Also your code does not compile for me (GCC 6) because you use cout without std:: or using namespace std;. So how does it compile on your system? You are also using math.h, in C++ you should rather use cmath.
After fixing this, I get the following output on my Fedora 24 with g++ in version 6.4.1:
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474
The 153 is included in there, so either your compiler has an error or your program has undefined behavior and therefore the error ensues.
I have looked at the definition for Armstrong numbers and did a really short Python implementation:
# Copyright © 2017 Martin Ueding <dev#martin-ueding.de>
# Licensed under the MIT/Expat license.
def is_armstrong(number):
digits = [int(letter) for letter in str(number)]
score = sum(digit**len(digits) for digit in digits)
return score == number
armstrong = list(filter(is_armstrong, range(10000)))
print(' '.join(map(str, armstrong)))
The output matches your C++ program on my machine exactly:
0 1 2 3 4 5 6 7 8 9 153 370 371 407 1634 8208 9474
Looking through your code I cannot spot undefined behavior, it looks sensible. First you count the number of digits, then you build up the sum. Perhaps you should try with other compilers like GCC, LLVM, or Ideone. Does Code Blocks ship their own compiler or do they use a system compiler? What operating system are you running?
You said that you are just learning to program. That's cool to hear! I hope you have a good C++ book or other resource. For C++, there is a lot of bad advice on the internet. Also make sure that you have a book that has at least C++11, everything else is badly outdated.
I have changed your program and created some short functions that do just one task such that it is easier to read and reason about. I am not sure whether you already know about functions, so don't worry if that seems to complicated for now :-).
#include <cmath>
#include <iostream>
int get_digit_count(int const number) {
int digits = 0;
int remainder = number;
while (remainder > 0) {
++digits;
remainder /= 10;
}
return digits;
}
bool is_armstrong_number(int const number) {
int const digit_count = get_digit_count(number);
int remainder = number;
int sum = 0;
while (remainder > 0) {
int const last_digit = remainder % 10;
sum += std::pow(last_digit, digit_count);
remainder /= 10;
}
return number == sum;
}
int main() {
for (int i = 0; i <= 10000; ++i) {
if (is_armstrong_number(i)) {
std::cout << i << ' ';
}
}
std::cout << std::endl;
}
This algorithm generates and prints out Armstrong numbers to 999, but can easily be expanded to any length using the same methodology.
n = 1; %initialize n, the global loop counter, to 1
for i = 1 : 10 %start i loop
for j = 1 : 10 %start j loop
for k = 1 : 10 %start k loop
rightnum = mod(n, 10); %isolate rightmost digit
midnum = mod(fix((n/10)), 10); %isolate middle digit
leftnum = fix(n/100); %isolate leftmost digit
if ((n < 10)) %calulate an for single-digit n's
an = rightnum;
end
if ((n > 9) & (n < 100)) %calculate an for 2-digit n's
an = fix(rightnum^2 + midnum^2);
end
if ((n > 99) & (n < 1000)) %calculate an for 3-digit n's
an = fix(leftnum^3 + midnum^3 + rightnum^3);
end
if (n == an) %if n = an display n and an
armstrongmatrix = [n an];
disp(armstrongmatrix);
end
n = n + 1; %increment the global loop counter and continue
end
end
end
You can use arrays:
#include<iostream>
using namespace std;
int pow(int, int);
int checkArm(int);
int main() {
int range;
cout<<"Enter the limit: ";
cin>>range;
for(int i{};i<=range;i++){
if(checkArm(i))
cout<<i<<endl;
}
return 0;
}
int pow(int base, int exp){
int i{0};
int temp{base};
if(exp!=0)
for(i;i<exp-1;i++)
base = base * temp;
else
base=1;
return base;
}
int checkArm(int num) {
int ar[10], ctr{0};
int tempDigits{num};
while(tempDigits>0){
tempDigits/=10;
ctr++;
}
int tempArr{num}, tempCtr{ctr};
for(int i{0};i<=ctr;i++){
ar[i] = tempArr / pow(10,tempCtr-1);
tempArr = tempArr % pow(10,tempCtr-1);
tempCtr--;
}
int sum{};
for(int k{};k<ctr;k++){
sum+=pow(ar[k],ctr);
}
if(sum==num)
return 1;
else
return 0;
}

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;

SIGSEGV "3n + 1"

100 - The 3n + 1 problem
http://www.spoj.com/problems/PROBTRES/
always i get this >>> runtime error (SIGSEGV) <<<
why plz help !
Background:
Problems in Computer Science are often classified as belonging to a certain class of problems (e.g., NP, Unsolvable, Recursive). In this problem you will be analyzing a property of an algorithm whose classification is not known for all possible inputs.
The Problem:
Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then n = 3n + 1
5. else n = n / 2
6. GOTO 2
Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)
Given an input n, it is possible to determine the number of numbers printed (including the 1). For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.
For any two numbers i and j you are to determine the maximum cycle length over all numbers between i and j.
The Input:
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.
You should process all pairs of integers and for each pair determine the maximum cycle length over all integers between and including i and j.
You can assume that no operation overflows a 32-bit integer.
The Output:
For each pair of input integers i and j you should output i, j, and the maximum cycle length for integers between and including i and j. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers i and j must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line).
Sample Input:
1 10
100 200
201 210
900 1000
Sample Output:
1 10 20
100 200 125
201 210 89
900 1000 174
#include <iostream>
using namespace std ;
long int a[1000001];
long int F (long int n){
if(a[n]!=0)
return a[n];
else {
if(n%2 !=0)
a[n]=F(n*3+1)+1 ;
else
a[n]=F(n/2)+1 ;
return a[n];
}
}
int main(){
a[1]= 1 ;
long int i , j , MX , MN , x=0 ;
while (cin>>i >> j ){
MX=max(i,j);
MN=min(i,j);
for(;MN<=MX;MN++){
if(x<F(MN))
x=F(MN) ;
}
cout<<i<<" "<<j<<" "<<x<<endl;
x= 0;
}
return 0 ;
}
what is the difference between this and my code ?!!!
#include <stdio.h>
#include <stdlib.h>
#define MAX 1000001
static int result[MAX];
int calculate(unsigned long i);
int main()
{
unsigned long int i = 0;
unsigned long int j = 0;
unsigned long int k = 0;
int max,x,y;
result[1] = result[0] = 1;
while (scanf("%ld",&i)!= EOF)
{
scanf("%ld",&j);
if (i > j)
{
x = i;
y = j;
}
else
{
x = j;
y = i;
}
max = 0;
for (k = y; k <= x; k++)
{
if (result[k] != 0 && result[k] > max)
max = result[k];
else if (calculate(k) > max)
max = result[k];
}
printf("%ld %\ld %d\n",i,j,max);
}
return 0;
}
int calculate(unsigned long i)
{
if (i < MAX && result[i])
return result[i];
if ( i % 2 == 1 )
{
if (i < MAX)
return result[i] = 2+calculate((3*i+1)/2);
else
return 2+calculate((3*i+1)/2);
}
else
{
if( i < MAX)
return result[i] = 1 + calculate(i / 2);
else
return 1 + calculate(i /2 );
}
}
You might check the actual range of values you're getting for n, as it might be stepping outside your array long a[1000001]. Also, you might check your recursion depth. If you recurse too deeply, you'll overflow the stack.
I would consider adding an assert to test n (ie. assert(n < 1000001)), and perhaps a recursion depth variable to check your recursion depth as the first steps to diagnosing and debugging this code. You can find assert in <cassert>.