A better approach to add big numbers, Project Euler #13 [closed] - c

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Project euler problem 13
For C program I tried the problem with practical approach, i.e. not defining the data in the code but rather using scanf for taking input.
But I cannot understand why the output is wrong! I get 1373762303 while it should be 5537376230.
It seems ok for 2-3 numbers.
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#define NUM 50
#define STRINGS 100
#define OUTPUT 10
int main(void) {
char str[STRINGS][NUM+1];
int answer[NUM+1] = {0};
int carry = 0, out_digits = OUTPUT;
for(int i = 0; i < STRINGS; i++){
scanf("%s", str[i]);
for(int j = NUM; j >=0; j--){
answer[j] += (str[i][j] - 48) + carry;
if(answer[j] > 9){
carry = answer[j] / 10;
answer[j] %= 10;
}else{
carry = 0;
}
}
}
printf("--------------------------------------------------\r\n");
printf("%d",carry);
for(int j = 0; j < OUTPUT-1; j++){
printf("%d",answer[j]);
}
printf("\r\n--------------------------------------------------");
return 0;
}

scanffills in the array you give it with a string constructed from the input including a null terminator byte. You allocate 51 bytes correctly but when you start adding the digits, you start at index 50 which is the index of the nul byte. The actual digits are from indexes 0 to 49.
This means that you will get a carry into the units digit of your answer at some point because the answer for that digit is calculated as
answer[50] += (str[i][50] - 48) + carry;
// ^^^^ correction applied for ASCII
Another issue is that you forget to reset carry to zero at the beginning of adding each new number.
This might work (not tested) but it still doesn't really handle overflows in the top digits
for(int i = 0; i < STRINGS; i++){
scanf("%s", str[i]);
carry = 0; // Reset the carry
for(int j = NUM - 1; j >=0; j--){
answer[j] += (str[i][j] - 48) + carry;
if(answer[j] > 9){
carry = answer[j] / 10;
answer[j] %= 10;
}else{
carry = 0;
}
}
}

I got the answer, it was the missing carry over when adding the two numbers. Following is the solution:
#include <stdio.h>
#include <ctype.h>
#include <strings.h>
#define NUM 50
#define STRINGS 100
#define OUTPUT 10
int main(void) {
char str[STRINGS][NUM+1];
int answer[NUM+1] = {0};
int carry = 0, out_digits = OUTPUT, intm_carry = 0;
for(int i = 0; i < STRINGS; i++){
scanf("%s", str[i]);
for(int j = NUM; j >=0; j--){
answer[j] += (str[i][j] - 48) + carry;
if(answer[j] > 9){
carry = answer[j] / 10;
answer[j] %= 10;
}else{
carry = 0;
}
}
intm_carry += carry;
carry = 0;
}
printf("--------------------------------------------------\r\n");
printf("%d", intm_carry);
for(int j = 0; j < OUTPUT-1; j++){
printf("%d",answer[j]);
}
printf("\r\n--------------------------------------------------");
return 0;
}

Related

How to convert each number in a num String to an int in C

I've been trying to do this problem on Project Euler
This is what I've done so far -
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
char nums[] = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450"
int64_t sum = 1, new_sum = 0;
int num;
for(int i = 0; i < 988; i+= 13){
sum = 1
for(int j = 0; j < 13; ++j){
//Converting nums[i] to int and storing it to num here
sum *= num;
}
if(sum > new_sum){
new_sum = sum;
}
}
printf("%lld", new_sum);
}
I don't know how to convert each charNum in the String to an integer, I've tried atoi and sscanf and both of them ask for a char pointer.
I get these errors respectively
passing argument to parameter here
int atoi(const char *); //sum *= atoi(nums[i])
format specifies type 'int *' but the argument has type 'int' [-Wformat]
sscanf(nums[i], "%d", num);
Any help is appreciated.
Just converting a character representing a digit to the digit itself is simply done by
int digit = nums[position] - '0';
C language guarantees for any character set that the digits 0-9 are succeeding one another in exactly that order (which is not necessarily the case for alphabetic characters, see e.g. (in-?) famous EBCDIC).
As I read the problem the maximum can be at any location, not only multiples of 13. For this speaks as well that the maximum of four subsequent digits is found at a location where the number of digits preceding is not a multiple of four.
Apart from, unless the number if digits is a multiple of 13, your loops would exceed array bounds of nums, so undefined behaviour (if not a multiple of 13, then for last iteration of i there are less than 13 digits left, but j still tries to iterate over all 13 digits).
Fixing both:
size_t sequenceLength = 13; // could be a function parameter
size_t len = strlen(nums); // sizeof would include the terminating 0 character!
if(len < sequenceLength)
{
return 0; // if within a function, else whatever appropriate error handling
}
uint64_t max = 1; // can't have negative values anyway...
for(size_t i = 0; i < sequenceLength; ++i)
{
max *= nums[i] - '0'; // see above
}
// now we found first possible maximum: the product of first 13 digits
uint64_t num = max;
for(size_t i = sequenceLength; i < len; ++i)
{
// for next product, we have already included the first 12 digits
// within the previous product!
// but there is one surplus digit contained we need to eliminate:
num /= nums[i - sequenceLength] - '0';
// now we can include the yet missing one:
num *= nums[i] - '0';
// or as a one-liner:
num = num / (nums[i - sequenceLength] - '0') * (nums[i] - '0');
// TODO: update maximum, if need be, just as in your code
}
Would you please try the following:
#include <stdio.h>
#include <stdlib.h>
#define N 13
int main() {
char nums[] = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
int64_t prod = 1, max_prod = 0;
int num;
int pos;
for (int i = 0; i < sizeof nums; i += N) {
prod = 1;
for (int j = 0; j < N; j++){
// Converting nums[i] to int and storing it to num here
num = nums[i + j] - '0';
prod *= num;
}
if (prod > max_prod) {
max_prod = prod;
pos = i;
}
}
printf("max product = %ld at %.*s\n", max_prod, N, nums + pos);
}
Output:
max product = 6270566400 at 4355766896648
BTW as the variable name sum is misleading, I've changed it to prod for product.
I assume that you want a nuber for each digit (i.e., range 0 to 9)
If yes, the below code should be not too far from what you need:
char nums[] = "73167176531330624919225119674426574742355349194934969835203... (so long)...";
char *p;
long lTheTotalCount, lTheNumber;
lTheTotalCount = 0;
for (p=nums ; *p ; p++) {
lTheNumber = (long)(*p - '0');
lTheTotalCount += lTheNumber;
};

Adding two numbers [1, 10^10000] as arrays of chars - C

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;
}

Program Bugs with large sequences (C) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am trying to code the Waterman algorithm in C.
Now when the length of the sequence exceeds 35 the program just lags.
I have no idea where to start looking, tried but got nothing worked out.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Max Function Prototype.
int maxfunction(int, int);
// Prototype of the random Sequences generator Function.
void gen_random(char *, const int);
int main(int argc, char *argv[]) {
// Looping variable and Sequences.
int i = 0, j = 0, k = 0;
char *X, *Y;
int length1, length2;
// Time Variables.
time_t beginning_time, end_time;
// Getting lengths of sequences
printf("Please provide the length of the first Sequence\n");
scanf("%d", &length1);
printf("Please provide the length of the second Sequence\n");
scanf("%d", &length2);
X = (char*)malloc(sizeof(char) * length1);
Y = (char*)malloc(sizeof(char) * length2);
int m = length1 + 1;
int n = length2 + 1;
int L[m][n];
int backtracking[m + n];
gen_random(X, length1);
gen_random(Y, length2);
printf("First Sequence\n");
for (i = 0; i < length1; i++) {
printf("%c\n", X[i]);
}
printf("\nSecond Sequence\n");
for (i = 0; i < length2; i++) {
printf("%c\n", Y[i]);
}
// Time calculation beginning.
beginning_time = clock();
// Main Part--Core of the algorithm.
for (i = 0; i <= m; i++) {
for (j = 0; j <= n; j++) {
if (i == 0 || j == 0) {
L[i][j] = 0;
} else
if (X[i-1] == Y[j-1]) {
L[i][j] = L[i-1][j-1] + 1;
backtracking[i] = L[i-1][j-1];
} else {
L[i][j] = maxfunction(L[i-1][j], L[i][j-1]);
backtracking[i] = maxfunction(L[i-1][j], L[i][j-1]);
}
}
}
// End time calculation.
end_time = clock();
for (i = 0; i < m; i++) {
printf(" ( ");
for (j = 0; j < n; j++) {
printf("%d ", L[i][j]);
}
printf(")\n");
}
// Printing out the result of backtracking.
printf("\n");
for (k = 0; k < m; k++) {
printf("%d\n", backtracking[k]);
}
printf("Consumed time: %lf", (double)(end_time - beginning_time));
return 0;
}
// Max Function.
int maxfunction(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
// Random Sequence Generator Function.
void gen_random(char *s, const int len) {
int i = 0;
static const char alphanum[] = "ACGT";
for (i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
}
Since you null terminate the sequence in gen_random with s[len] = 0;, you should allocate 1 more byte for each sequence:
X = malloc(sizeof(*X) * (length1 + 1));
Y = malloc(sizeof(*Y) * (length2 + 1));
But since you define variable length arrays for other variables, you might as well define these as:
char X[length1 + 1], Y[length2 + 1];
Yet something else is causing a crash on my laptop: your nested loops iterate from i = 0 to i <= m, and j = 0 to j <= n. That's one step too many, you index out of bounds into L.
Here is a corrected version:
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
The resulting code executes very quickly, its complexity is O(m*n) in both time and space, but m and n are reasonably small at 35. It runs in less than 50ms for 1000 x 1000.
Whether it implements Smith-Waterman's algorithm correctly is another question.

adding leading zeros to decimal to binary array C

I am converting decimal to binary and I need my output to be 32 (bits?) long. This works as I intend, but I am not getting the leading zeros, for instance, the input "3" gives me "11", instead of "00000000000000000000000000000011"
int i = 0;
int bi[31];
while(num > 0){
if(num % 2 == 0)
bi[i] = 0;
else
bi[i] = 1;
i++;
num = num / 2;
}
for(int j = i - 1; j >= 0; j--){
printf("%d", bi[j]);
}
I originally thought this would be as simple as changing my printout to just loop down from 31 to 0 and print out all the contents of the array, assuming zeros would be in everything not in my bi[] array. But that does not work :)
Thanks
for(int j = 0; j < 32; j++) // this for loop is initializing all the places with zeroes
{
b[j] = 0;
}
i = 31 // starting from the leftmost place of the array
while(num > 0) //as the values in the array gets updated the remaining place is left with trailing
{
if(num % 2 == 0)
bi[i] = 0;
else
bi[i] = 1;
i--;
num = num / 2;
} zeroes
for(int j = 0; j < 32; j++){
printf("%d", bi[j]);
}
Due to the LIFO nature of this problem, consider a recursive (stack-based) solution:
#include <stdio.h>
#include <limits.h>
void recFoo(int num,int index)
{
if (index > 0)
recFoo(num/2, index-1);
printf("%d", num%2);
}
void foo(int num)
{
recFoo(num, sizeof(num)*CHAR_BIT);
}
The reson is because the first loop only loops twice, which is the highest set bit in the input. The first loop needs to loop unconditionally the number of bits you want, and so should the printing loop.
First of all you need a 32 long array. Try this one..... Initializing your array
void foo (int num) {
int i = 31;
int bi[32] = {0};
while(num > 0){
if(num % 2 == 0)
bi[i] = 0;
else
bi[i] = 1;
i--;
num = num / 2;
}
for(int j = i - 1; j >= 0; j--){
printf("%d", bi[j]);
}

simplifying nested for loop in C

I am looking for a narcissistic number with 3 to 9 digits. I have working code, but the use of nested loops is cumbersome. I think I could use recursion, how?
#include "stdafx.h"
#include <time.h>
int power(int a,int b)
{
int t=1,i;
for (i=0;i<b;i++)
t*=a;
return t;
}
int _tmain(int argc, _TCHAR* argv[])
{
double t0=clock();
int a,b,c,d,e,f,g,h,i;
int len=9;
for (a=1;a<=9;a++)
for (b=0;b<=9;b++)
for (c=0;c<=9;c++)
for (d=0;d<=9;d++)
for (e=0;e<=9;e++)
for (f=0;f<=9;f++)
for (g=0;g<=9;g++)
for (h=0;h<=9;h++)
for(i=0;i<=9;i++)
{
int num=10*(10*(1000000*a+100000*b+10000*c+1000*d+100*e+10*f+g)+h)+i;
if (num==power(a,len)+power(b,len)+power(c,len)+power(d,len)+power(e,len)+power(f,len)+power(g,len)+power(h,len)+power(i,len))
printf(" %d ",num);
}
printf("\n耗时: %f s",(clock()-t0)/CLOCKS_PER_SEC);
return 0;
}
Your num is simply iterating through all numbers from 0 (See Edit 2) to 999,999,999. So you really don't need to iterator over every digit. A simple way of doing what you want, even though probably not anymore efficient is this:
unsigned int num;
for (num = 0; num < 1000000000; ++num) // will take long
{
char digits[15];
unsigned int i, other_num;
sprintf(digits, "%09u", i); // division used here
other_num = 0;
for (j = 0; j < 9; ++j)
other_num += power(digits[j] - '0', len);
if (num == other_num)
printf(" %d ",num);
}
Note that you can do your power function in a more efficient way. See this question.
Edit 1: (Note: see Edit 2)
I am reading through the wikipedia page, and it turns out that you shouldn't set len to 9, because if you have for example 153, the other_num should be 1^3 + 5^3 + 3^3 (example from Wikipedia).
So you should adjust the loop in the following way:
unsigned int num;
for (num = 0; num < 1000000000; ++num)
{
char digits[15];
unsigned int i, other_num, len;
len = snprintf(digits, 10, "%u", i); // len returned by snprintf
other_num = 0;
for (j = 0; j < len; ++j) // changed 9 to len
other_num += power(digits[j] - '0', len);
if (num == other_num)
printf(" %d ",num);
}
Edit 2:
I just noticed that your number starts from 100,000,000, so you don't really need to pay attention to Edit 1. Nevertheless, I believe it's good to know it in case you needed to change the range of your numbers.
Wonderful loop.
What about this:
for( num = 100000000; num <= 999999999; num++ ) {
int compare = 0;
for( k = 0; k < 10; k++ ) {
int position = pow(10, k+1);
int s = num%position;
compare += pow(s, 9);
}
if( num == compare ) {
printf("%d\n", num);
}
}
Of course, check for boundaries :)
Actually, you are inspecting all values (num) from 1 to 10^len, if I am not mistaken.
So, a simple for cycle from 1 to 10^len would be enough. Then you can take the digits from num and calculate the power value.
I would strongly suggest to calculate the powers 1^len, 2^len ... 9^len first and put them into an array. It will greatly improve performance.

Resources