wrong result in adding huge numbers in c - c

I want to add some huge numbers which I am gonna input from the keyboard. However I want to input them as a string. I've tried a different way with the ASCII which was written in another answer but it doesn't seem to work. Anyway here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
/* ADDING HUGE NUMBERS */
int addHugeNumbers(char *a1,char *a2,char *res){
int i,q,e; // k is the add
int k;
k=0;
i=0;
q=0;
e=strlen(a1);
while (i<e-1) //CHECK IF THE FIRST ONE IS ONLY DIGITS
{
if (isdigit(a1[i])==0) return 0;
else i++;
}
i=0;
q=strlen(a2);
while (i<q-1) //SAME CHECK FOR THE SECOND ONE
{
if (isdigit(a2[i])==0) return 0;
else i++;
}
k=atoi(a1)+atoi(a2);
sprintf(res,"%d",k);
puts(res);
return 1;
}
int main(int argc, char *argv[]) {
char a1[2000], a2[2000],res[2000];
fgets(a1,2000,stdin);
fgets(a2,2000,stdin);
printf("%d",addHugeNumbers(a1,a2,res));
return 0;
}
This code works just fine with small numbers (lets say up to 5-6 digits). But then when it comes to bigger numbers (15-16) it gives me wrong answers.
Try to add 9999999999999999 + 9999999999999999

Rightly said that C has no built-in support for arbitrarily huge numbers.
So if there is really a need to add huge numbers input as strings, then write your own function for summing them up by adding unit digits, tens digits, hundreds digits and so on keeping in mind to accommodate the carry if any.

Related

Floating point exception (core dumped) - Non-square numbers finder

i have a problem. I've been making this for hours, and i finally thought i had a draft, i solved a few mistakes i made, but now it's typing out "Floating point exception (core dumped)" when i run it. I was able to solve a few other issues, but I don't think i can get over this one without basically starting from scratch, i have no idea what could be causing this, i wonder if any more knowledgeable people here could take a look and try to spot a possible mistake. My program is supposed to find Non-square numbers - numbers not divisible by squares of whole numbers. It first finds squares to divide by, and then divides Non-square number candidates up to a specified integer. Then it types out all the numbers it finds. I think it's quite possible i've made a mistake in pointer usage, i have not yet quite mastered those, and most likely couldn't solve a related issue anyway.
#include <stdio.h>
#include <limits.h>
#include <math.h>
#include <stdlib.h>
int isNonSq (int a,int sqr) {
int b=0.75*a;
for (int i=2;i<b;i++) {
if (a%sqr[i]==0) return 0;
}
return 1;
}
int main ( void ) {
int a;
int * resNum;
int * sqr;
while (!feof(stdin)) {
if (scanf(" %d",&a)!=1||a<=0) {
printf("Nespravny vstup.\n");
return 0;
} else {
int b, c=1;
b=0.75*a;
resNum=(int)malloc(a*sizeof(resNum));
sqr=(int)malloc(a*sizeof(*sqr));
for (int i=2;i<sqrt(a);i++)
sqr[i]=pow(i,2);
for (int i=1;i<b;i++) {
if (isNonSq(i,sqr)) {
resNum[c]=i;
c++;
}
}
}
}
for (int i=1;i<a;i++) {
printf(" %d",resNum[i]);
}
printf("\n");
free(resNum);
free(sqr);
return 0;
}
This could be occurring because of an NaN or an infinite number, I would recommend you use gdb to figure out what is happening when you run your compiled c code. https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.php
Goodluck!

Two almost exactly the same programs but different output

Hi I have made a very simple program that should work but it don't:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(int argc, char *argv[]) {
int usedNumbers[256];
memset(usedNumbers,0,256);
srand(time(NULL));
for(int i=0; i<256; ++i){
while(1){
int r = rand()%256;
if( !usedNumbers[r] ){
usedNumbers[r] = 1;
break;
}
printf("Test: %03d -> %03d\n", i, r);
}
}
return 0;
}
The idea of the program is to print numbers from 0 to 255 on the screen in the random order but the program stops on 84th number on 32 computers and 144th number on 64 bit computers. If i only move the "int usedNumbers[256];" above the function like that:
#include <string.h>
int usedNumbers[256];
int main(int argc, char *argv[]) {
Program works as it supposed to.
Why is it that?
I am using the newest GNU/GCC compiler and C11 standard.
The usedNumbers inside main is a local variable and these are not zero-initialized (i.e. they can contain garbage). Since you only use memset(..., 256), only the first 256 bytes are zero-initialized, and the rest (e.g. half or three quarters of the array -- or more, depending on the size of int) is not.
The usedNumbers outside main is a global variable, however, and these are completely zero-initialized, even without memset. So there, you really have an empty array with no garbage in it, and that is why that works as expected.
So do:
memset(usedNumbers, 0, sizeof(usedNumbers));
and both versions should produce the same, expected result.

Appropriate data type to be used in a C program

I'm trying to run a program that does certain operations on factorials of large numbers (say 50!; viz 3.041e+64 - huge!) and therefore doesn't fit in the normal int data types that I'm aware of(unsigned long long int etc)
Which data type do I use to store these values?
P.S I was trying to find the trailing zeroes in a factorial. The following was my approach:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int FactorialFinder(int a)
{
if (a>1)
a= a* (FactorialFinder(a-1)) ;
return a;
}
int main()
{
printf("Enter number \n");
int num ;
scanf("%d",&num) ;
printf("number is %d\n",num);
printf("Factorial is %d",(num = FactorialFinder(num))) ;
int x=0, count = 0 ;
while(num>0)
{
x = (num%10) ;
if (x == 0)
count++ ;
else
break;
num= num/10 ;
}
printf("\nNumber of trailing zeroes is %d",count) ;
getchar() ;
return 0;
}
Works fine upto 12! beyond which the results are erroneous (from 17! it starts returning negative factorial values(?), from 34! it gives 0) I'm guessing due to the datatype problem. Can someone help me out?
Well these kind of numbers cannot be stored as single number rightly as you've reasoned there are no data types to hold them. The best way to work with large numbers is to store them as arrays of int type or char type.
for example you can store 1234567898765 as an array int big[14] where,
big[0]=1
big[1]=2
.
.
.
big[13]=5 //last element
big[14]=-1 //to mark the end of number...
or in the reverse order with -1 as last element (select which is is convenient for your implementation)
and now comes the challenging part where you have to create functions for addition, subtraction, multiplication and other operations which you require.. There are many ways of implementing these function..give a try.. or you can just look up how to do them here's a source : click
this provides a implementation of arithmetic numbers for up to 100 digit numbers however you can try to build one which can deal with even larger numbers :)

power int number while in loop

OK, so my task is to get a single digit from a natural number and sum the square numbers (Using function while, which means no arrays yet :S). For instance I type 123 so sum=1*100+2*10+3*1; However the problem is that the digit could be whatever. My problem is that the power rises with int but its like so - 1, 10, 99, 1000. The problem for me is 99. Also answer is looping but I'll fix it later. Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int N,
number=0,
answer=0,
a=1,
i=0;
printf("Type natural number: ");
scanf("%d",&N);
while(N>i)
{
number=N%10;
N/=10;
a=10;
a=pow(a,i);
answer+=number*number*a;
printf("%d\n", answer);
i++;
}
return 0;
}
Try it the other way around. Don't make the input an integer. Start at the beginning of the stream, get the character, convert it to an int 'number'. Then do
answer = 10 * answer;
answer += (number * number);
This will build up your answer little by little. Note that I am not sure that this is what you are asking for due to your example not seeming to match the code.
Let me know if this is off-base and I will update it.

Please help. The program for generating random numbers is not working

I am writing a program which have to generate N random not repeating numbers
the prototype should be voidrandom_int(int array[], int N);
it is not having any errors but it is not working. Not even giving any number
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void random_init(int array[], int N)
{
srand(time(NULL));
int i, j;
array[0]=rand()%N;
for(i=1;i<N;i++)
{
array[i]=rand()%N;
if(array[i]==0)
array[i]=1;
for(j=0;j<i;j++)
{
if(array[i]==array[j])
break;
}
if((i-j)==1)
continue;
else
i--;
}
}
int main(void)
{
int a[5], i, N;
N=5;
random_init(a,N);
for(i=0;i<N;i++)
printf("%d ", a[i]);
return 0;
}
This part makes no sense:
if(array[i]==0)
array[i]=1;
It will limit your choices to N-1 numbers (1 to N-1), out of which you try to find N numbers without repetition - leading to an infinite loop.
if((i-j)==1)
continue;
Here you probably want if (i==j) instead, to check if the previous loop ran to completion.
A faster and simpler way to generate the numbers 0..N-1 in a random order, is to put these numbers in an array (in sequential order), and then use Fisher-Yates Shuffle to shuffle the array.
This method is biased. Do not use it other than for educational purposes.
Other than Ficher-Yates, which uses another array, you can use the method of going through all the available numbers and find a "random" spot for them (effectively "initializing" the array twice). If the spot is taken, choose the next one. Something like this, in pseudo-code:
fill array with N
for all numbers from 0 to N-1
find a random spot
while spot is taken (value is N) consider next spot /* mind wrapping */
set value in current spot

Resources