I'm trying to make a program using C lang to calculate the given two numbers, A and B, how many numbers from A to B, inclusive, are divisible by another number K. For example, if A is 1, B is 10, and K is 3, then there are 3 numbers that satisfy this: 3, 6, and 9.
when trying to debug it in online compiler i get this error:
Program received signal SIGFPE, Arithmetic exception.
0x00005555555553fd in main () at main.c:346
346 int temp = j % newArr[j][2];
is there anything wrong in the modulo?
this is my current my attempt. i've tried this injs and it works, but not in C
int main(void)
{
int arr[] = {100,16,9905,8,7346,...,301n]
//the input is array 0f 301 integers, which the
first element is just the number of test case
int newArr[100][3];
int no = 1;
int result = 0;
int x, y, i, j;
int start, end;
for (x = 0; x < 100; x++)
{
for (y = 0; y < 3; y++)
{
newArr[x][y] = arr[no];
no += 1;
}
}
for (i = 0; i < 100; i++)
{
if (newArr[i][0] < newArr[i][1])
{
start = newArr[i][0];
end = newArr[i][1];
}
else
{
start = newArr[i][1];
end = newArr[i][0];
}
for (j = start; j <= end; j++)
{
int temp = j % newArr[j][2];
if ( temp == 0)
{
result += 1;
}
printf(" %d result %d\n",i, result);
}
printf("case %d : %d \n", i, result);
result = 0;
}
return 0;
}
thanks in advance!
There is no technical issue here: you have mixed up i and j
int temp = j % newArr[j][2];
should become
int temp = j % newArr[i][2];
Related
How do I make my code more efficient (in time) pertaining to a competitive coding question (source: codechef starters 73 div 4):
(Problem) Chef has an array A of length N. Chef wants to append a non-negative integer X to the array A such that the bitwise OR of the entire array becomes = Y .
Determine the minimum possible value of X. If no possible value of X exists, output -1.
Input Format
The first line contains a single integer T — the number of test cases. Then the test cases follow.
The first line of each test case contains two integers N and Y — the size of the array A and final bitwise OR of the array A.
The second line of each test case contains N space-separated integers A_1, A_2, ..., A_N denoting the array A.
Please don't judge me for my choice of language .
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int* binary_number(int n) // returns pointer to a array of length 20(based on given constrains) representing binary
{
int* ptc;
ptc = (int*) malloc(20*sizeof(int));
for(int i = 0; i < 20; i++)
{
if((n / (int) pow(2,19-i)) > 0){*(ptc + i) = 1;}
else {*(ptc + i) = 0;}
n = n % (int) pow(2,19-i) ;
}
return ptc;
}
int or_value(int* ptc, int n) // Takes in pointers containing 1 or zero and gives the logical OR
{
for(int k = 0; k < n; n++)
{
if(*ptc == *(ptc + 20*k)){continue;} // pointers are 20 units apart
else{return 1;break;}
}
return *ptc;
}
int main(void) {
int t; scanf("%d", &t);
for (int i = 0; i < t; i++)
{
int n, y;
scanf("%d %d", &n, &y);
int a[n];
for(int j = 0; j < n ; j++)
{
scanf("%d", &a[j]);
}
int b[20*n];
for (int j = 0; j < n; j++)
{
for (int k = 0; k < 20; k++)
{
b[20*j + k] = *(binary_number(a[n])+k);
}
}
int c = 0;
int p = 0;
for (int j = 0; j < 20; j++)
{
if ((*(binary_number(y) + j) == 1) && (or_value((&b[0] + j),n) == 0)){c = c + pow(2,19 - j);}
else if ((*(binary_number(y) + j) == 0) && (or_value((&b[0] + j),n) == 1)){p = 1; break;}
}
if (p==1){printf("-1");}
else {printf("%d\n", c);}
}
return 0;
}
I have to solve a problem where one of the important tasks is to reorder the digits of the input in ascending order and we are not allowed to use arrays and lists. I have no problem with that and my code works, but only if we do not consider leading 0, which we should in this problem. The only way I see how to do is to check digit by digit and then add then ordered by multiplying the number by 10 and adding the next digit. (1*10 = 10, 10+3= 13, we got 1 and 3 ordered) However, if we have a 0 in our number this method will not work because if I want to make 0123 with the * 10 method, I won't be able to have the 0 as the first digit never. Does anyone know how to solve this? My code is below:
int ascendingNumbers (int n) { //This function sorts the number on an ascending order
int number = n;
int sortedN = 0;
for (int i = 0; i <= 9; i++) {
int toSortNumber = number;
for (int x = 0; x <= 4; x++) {
int digit = toSortNumber % 10;
if (digit == i) {
if (digit == 0) {
sortedN==10;
}
sortedN *= 10;
sortedN += digit;
}
toSortNumber /= 10;
}
}
return sortedN;
}
Normally I don't do homework problems, but for especially awful ones I'll make an exception.
(Also I'm making an exception to my general rule not to have anything to do with these absurd "desert island" constraints, where you're stranded after a shipwreck and your C compiler's array functionality got damaged in the storm, or something.)
I assume you're allowed to call functions. In that case:
#include <stdio.h>
/* count the number of digits 'd' in 'n'. */
int countdigits(int n, int d)
{
int ret = 0;
/* do/while so consider "0" as "0", not nothing */
do {
if(n % 10 == d) ret++;
n /= 10;
} while(n > 0);
return ret;
}
int main()
{
int i, n;
printf("enter your number:\n");
scanf("%d", &n);
printf("digits: ");
for(i = 0; i < 10; i++) {
int n2 = countdigits(n, i);
int j;
for(j = 0; j < n2; j++) putchar('0' + i);
}
printf("\n");
}
This solution does not involve a function int ascendingNumbers() as you asked about. If you want to handle leading zeroes, as explained in the comments, you can't do it with a function that returns an int.
Your zero problem is solved, check it...
class Main {
public static void main(String[] args) {
int number = 24035217;
int n = number, count = 0;
int sortedN = 0;
while (n != 0) {
n = n / 10;
++count;
}
for (int i = 9; i >= 0; i--) {
int toSortNumber = number;
for (int x = 1; x <= count; x++) {
int digit = toSortNumber % 10;
// printf("\nBefore i = %d, x = %d, toSortNumber = %d, sortedN = %d, digit = %d",i,x,toSortNumber,sortedN,digit);
if (digit == i) {
sortedN *= 10;
sortedN += digit;
}
// printf("\nAfter i = %d, x = %d, toSortNumber = %d, sortedN = %d, digit = %d",i,x,toSortNumber,sortedN,digit);
toSortNumber /= 10;
}
}
System.out.print(sortedN);
}
}
The purpose of the program is to create a random list of 1000 numbers in an array, sort that array, then find the greatest set of numbers within (x, x+50). The program successfully generates and sorts the numbers within the array, but crashes when the (i, j) set finding algorithm starts. The program generates no errors on compiling, and I'm sure the error is simple, but for the life of me I can't find the issue. Thanks in advance you amazing people!
int main( ){
int a, b, temp, i, j, x, y, tempTotal, arrayStartMax;
int finalTotal = 0;
int *info[ARRAY_FULL];
for (i=0; i<ARRAY_FULL; i++){
info[i]=(int*)malloc(sizeof(int));
*info[i]=rand()%1000;
}
for (a = 0; a < ARRAY_FULL; ++a){
for (b = a + 1; b < ARRAY_FULL; ++b){
if (*info[a] > *info[b]){
temp = *info[a];
*info[a] = *info[b];
*info[b] = temp;
}
}
}
for (i=0; i<ARRAY_FULL; i++){
printf("%d\n", *info[i]);
}
for (i = 0; i <= ARRAY_HALF; i++){
x = *info[i];
y = x+ARRAY_HALF;
tempTotal = 0;
for (j = i; j < i+ARRAY_HALF; i++){
if (*info[j] >= x || *info[j] <= y) {
tempTotal++;
}
if (tempTotal > finalTotal) {
arrayStartMax = *info[i];
finalTotal = tempTotal;
}
}
}
printf("Interval should start at %d for maximum numbers in a set.", arrayStartMax);
}
For the purpose of this program I would like to mention that ARRAY_FULL = 100 and ARRAY_HALF = 50.
Your code is throwing segfault because you're walking i out of bounds in this for loop.
for (j = i; j < i+ARRAY_HALF; i++){
if (*info[j] >= x || *info[j] <= y) {
tempTotal++;
}
if (tempTotal > finalTotal) {
arrayStartMax = *info[i];
finalTotal = tempTotal;
}
You set j = i then increment i prior to the comparison. So j will always be less than i.
Limit i in the comparison section of the for loop and it won't segfault.
I don't think the comparison is doing what you want, but you should be able to find your way home from here.
I tackled the problem by first figuring out the length of two given numbers and aligning the one with less digits (if one exists) into a new array so that the ones, tens, hundreds etc. align with the bigger number's ones, tens, hundreds, etc.
Then I wanted to save the sum of each two aligned elements (with a mod of 10) into a new array while checking if the sum of digits is greater than 10 - just the basic sum stuff. Now the problem occurs with adding two elements into the aplusb integer and I've tried fixing it with writing
int aplusb = (lengthA[max-i]-'0') +(temp[max-i]-'0');
but it doesn't work. I'm stuck and I don't know what to do. Please help.
The whole code:
#include <stdio.h>
#include <math.h>
int main(){
char a[10000];
char b[10000];
scanf("%s %s", &a, &b);
char sum[10000];
int lengthA = 0;
int lengthB = 0;
int i = 0;
while(a[i]){
i++;
} lengthA = i;
i = 0;
while(b[i]){
i++;
} lengthB = i;
char temp[10000];
int aplusb;
int carry = 0;
int max = lengthA;
int difference = abs(lengthA - lengthB);
if(lengthA>lengthB){
for(i=0; i<lengthA; i++){
temp[i+difference]=b[i];
}
for(i=0; i<=max; i++){
aplusb = lengthA[max-i]+temp[max-i]; //<-- this is the problematic line
if(carry = 1) aplusb++;
if(aplusb>9){
carry = 1;
aplusb%=10;
}
sum[i]=aplusb;
}
}
for(i=0; i<=max; i++){
printf("%c", sum[i]);
}
/*
if(lengthB>lengthA){
max = lengthB;
for(i=0; i<lengthB; i++){
temp[i+difference]=a[i];
}
}*/
return 0;
}
Doing operations and storing on very large numbers is very akin to doing operations and storing polynomials, i.e. with x = 10. a0 + a1.10 + a2.10^2 ... + an.10^n.
There are many polynomial libraries on the Internet, where you could find inspiration. All operations on your very large numbers can be expressed in terms of polynomials. This means that by using base 2^8, or even base 2^63, instead of base 10 to internally store your large numbers you would greatly improve performance.
You must also normalize your coefficients after operations to keep them positive. Operations may result in a negative coefficient, That can easily be fixed, as it is very similar to borrowing after a subtraction, this means coefficients must be larger than your base by 1bit.
To convert back to base 10, you'd need to solve r (your result) for v (your value), such as r(10)=v(2^63). This has only one solution, if you enforce the positive coefficients rule.
[note] After thinking about it some more: the rule on positive coefficients may only be necessary for printing, after all.
Example: adding. no memory error checking
int addPolys(signed char** result, int na, const signed char* a, int nb, const signed char* b)
{
int i, nr, nmin, carry, *r;
nr = max(na, nb) + 1;
nmin = min(na, nb);
r = malloc(sizeof(signed char) * (na + nb + 1));
if (nb < na)
{
nr = nb;
}
for (i = 0; i < nmin; ++i)
{
r[i] = a[i] + b[i];
}
for (; i < na; ++i)
{
r[i] = a[i];
}
for (; i < nb; ++i)
{
r[i] = b[i];
}
r[nr - 1] = 0;
// carry - should really be a proc of its own, unoptimized
carry = 0;
for (i = 0; i < nr; ++i)
{
r[i] += carry;
if (r[i] > 10)
{
carry = r[i] / 10;
r[i] %= 10;
}
else if (r[i] < 0)
{
carry = (r[i] / 10) - 1;
r[i] -= (carry * 10);
}
else
carry = 0;
}
// 'remove' leading zeroes
for (i = nr - 1; i > 0; --i)
{
if (r[i] != 0) break;
}
++i;
*result = r;
if (i != nr)
{
*result = realloc(i * sizeof(signed char));
}
return i; // return number of digits (0 being 1 digit long)
}
That code is working now for any two positive numbers with up to ten thousand digits:
#include <stdio.h>
#include <math.h>
#include <string.h>
int main(){
char chara[10000];
char charb[10000];
scanf("%s %s", &chara, &charb);
int lengthA = strlen(chara);
int lengthB = strlen(charb);
int max = lengthA;
if(lengthB>lengthA) max=lengthB;
int dif = abs(lengthA - lengthB);
//ustvari int tabele
int a[max];
int b[max];
int sum[max+1];
// nastavi nule
int i;
for(i=0; i<max; i++){
a[i] = 0;
b[i] = 0;
sum[i] = 0;
} sum[max] = 0;
//prekopiraj stevila iz char v int tabele &obrni vrstni red
for(i=0; i<lengthA; i++){
a[i] = chara[lengthA-i-1]-'0';
}
for(i=0; i<lengthB; i++){
b[i] = charb[lengthB-i-1]-'0';
}
int vsota;
int prenos = 0;
for(i=0; i<max; i++){
vsota = a[i]+b[i] + prenos;
if(vsota>=10) prenos = 1;
else if (vsota<10) prenos = 0;
sum[i]=vsota%10;
}
if(prenos==1){
sum[max] = 1;
for(i = max; i>=0; i--){
printf("%d", sum[i]);
}
} else {
for(i = max-1; i>=0; i--){
printf("%d", sum[i]);
}
}
return 0;
}
I'm working on an assignment for a programming class and am having an issue with a program. The goal is to take in a set of user defined values, store them in an array, then find the closest pair of numbers (the numbers with the smallest difference). The numbers don't have to have consecutive indices. Also, the array size of 50 is defined in the assignment by the professor.
The problem I'm running into is that the program will compile in both Linux (Ubuntu 14.xx) and Windows 10, however, when I run the result in Linux, it works fine but in Windows it outputs nothing.
This is the first time I've had this issue and as far as I know I didn't use any system specific commands. Any help provided would be appreciated.
Code:
#include <stdio.h>
int main()
{
int i, j, a, b, temp, mindiff, count;
int numarray[50];
count = 0;
for (i = 0; i < 50; i++)
{
scanf("%d", &numarray[i]);
count++;
if (numarray[i] == -1)
{
numarray[i] = 0;
count--;
break;
}
}
mindiff = 100;
for (i = 0; i < count; i++)
{
for (j = 0; j < count; j++)
{
a = numarray[i];
b = numarray[j];
if (a != b)
if (a > b)
temp = a - b;
else
temp = b - a;
if (temp < mindiff)
mindiff = temp;
}
}
for (i = 0; i < count; i++)
{
for (j = 0; j < count; j++)
{
a = numarray[i];
b = numarray[j];
if (a != b)
{
if (a > b && (a - b) == mindiff)
{
printf("Closest pair: %d and %d, Difference: %d\n", a, b, mindiff);
return 0;
}
}
}
}
return 0;
}
There are at least two major problems:
Your code has undefined behavior because you use temp even if it has not been set (you should start a block after if (a != b)). undefined behavior means anything can happen, including apparent success on Linux and failure on Windows.
You initialize mindiff to 100. If all numbers are farther apart from each other, mindiff will not be changed and the second loop will not print anything.
Here is a simpler version:
#include <stdio.h>
int main(void) {
int count, i, j, mina, minb, mindiff;
int numarray[50];
for (count = 0; count < 50; count++) {
if (scanf("%d", &numarray[count]) != 1 || numarray[count] == -1)
break;
}
mindiff = mina = minb = 0;
for (i = 0; i < count; i++) {
for (j = 0; j < count; j++) {
int a = numarray[i];
int b = numarray[j];
if (a > b) {
int diff = a - b;
if (mindiff == 0 || mindiff > diff) {
mindiff = diff;
mina = a;
minb = b;
}
}
}
}
if (mindiff == 0) {
if (count == 0) {
printf("No numbers input\n");
} else {
printf("The numbers are all identical\n");
}
} else {
printf("Closest pair: %d and %d, Difference: %d\n",
mina, minb, mindiff);
}
return 0;
}
You have the following problem:
Note: temp is considered a stack variable under the main function and since you do not initialize it, it becomes garbarge (for example a large negative number):
int i, j, a, b, temp, mindiff, count;
Then if temp is a large negative number, mindiff = the garbarge value of mindiff,
if (temp < mindiff)
mindiff = temp;
And the following if statement is always false.
if (a > b && (a - b) == mindiff)
And nothing gets printed.