c: a.exe has stopped working - c

I am learning how to program in c:
I want to create a program that separates a number into digits, from there I want to store them into an array (which I've already done in the code below). From there I need to print out the number by using the digits to help with producing the same number. The program crashed upon running and I don't know why.
#include <stdio.h>
int power(int a, int b);
int main()
{
//Issue: printing out incorrect numbers
//Fix: Recall that c is treated as a character here when getchar is invoked
#define MAX_SIZE 100
const int TEN = 10;
const int ONE = 1;
int c;
int digitPos, digitHolder, numberPower = 0;
int my_strg[MAX_SIZE];
printf("\n");
while (((c = getchar()) != EOF) && (c != '\n'))
{
my_strg[digitPos] = c - '0';
digitPos = digitPos + ONE;
}
while (digitPos >= 0)
{
int toPower = digitPos - 1;
printf("%10d", power(TEN, toPower));
digitPos = digitPos - 1;
}
return 0;
}
int power(int a, int b)
{
if (b == 0)
{
return 1;
}
else
{
return a * power(a, b - 1);
}
}
Currently the output is the powers required to return the inputted number, but after the print, the program crashes. Could someone please guide me in the right direction as to how I can fix this problem?

Change the while condition while (digitPos >= 0) into while (digitPos > 0)
Because when digipos==0 --> toPower==-1 --> power(TEN, toPower) CRASH
Beside that tiny problem your code is fine

Related

How can i stop this program by giving some input?

I was trying to filter out integers from input, without using getchar() function,
To be exact, i was trying to read coefficients and powers from 1x^2 + 3x^6 + 5x^0, that's when i ended up writing this program, it is not complete program, it was supposed to be a part of program .
int main(){
int a , b, i = 0, n;
char c[2];
while(5){
if(scanf("%1s", c) == 1){
if( (n = atoi(c)) != 0 || (*c == 48) ){
printf("%d", n);
}
}
}
return 0;
}
so what is correct way of doing it?
what are some modifications?
thanks :)
if this 1x^2 + 3x^6 + 5x^0 is your exact input, you can use scanf to scan it.
int powers[3];
int coefficients[3];
if (scanf("%dx^%d + %dx^%d + %dx^%d", &coefficients[0], &powers[0], &coefficients[1], &powers[1], &coefficients[2], &powers[2]) != 6)
{
exit(EXIT_FAILURE);
}

How do I generate a series of number with unique digits in C?

I've been at this problem for a day now and it feels like I'm getting nowhere.
What I want to do:
Generate all possible combinations of a nine-digit number between 1-9, but no digits can be the same. In other words, my goal is to generate exactly 362880 (9!) numbers, each one unique from one another and each number must contain only one of each digits. There should be no randomness involved.
What I want:
123456789
213796485
What I DON'T want:
111111111
113456789
What I've tried:
I start by creating an array to store the digits.
float num[9];
Using the principle that I num[0] can be any of the 9 digits, and num[8] has to be the one remaining, I tried nesting loops. I'll post the code, but there's no need to point out why it doesn't work because I already know why. However, I don't know how to fix it.
for (int a = 1; a < 10; a++) {
num[0] = a;
for (int b = 1; b < 9; b++) {
if (b != a)
num[1] = b;
// The code in between follows the same pattern
for (int i = 1; i < 2; i++) {
if (i != a && i != b && i != c && i != d && i != e && i != f && i != g && i != h) {
num[8] = i;
}
}
}
}
So as you can see, the last digit will always be 1, the second digit can never be 9 and so on.
So what options do I have? I tried making it so that it loops a total of 9^9 times, which would fix the problem I mentioned, but that's of course way too inefficient (and it didn't quite work as intended either).
Any ideas? I feel like it should be an easy thing to solve but I can't seem to be able to wrap my head around it.
Here is a simple solution that generates the 362880 permutations in lexicographical order:
#include <stdio.h>
#include <string.h>
void perm9(char *dest, int i) {
if (i == 9) {
printf("%.9s\n", dest);
} else {
for (char c = '1'; c <= '9'; c++) {
if (memchr(dest, c, i) == NULL) {
dest[i] = c;
perm9(dest, i + 1);
}
}
}
}
int main(void) {
char dest[9];
perm9(dest, 0);
return 0;
}

ASCII Characters Messed Up in simple C Program [duplicate]

This question already has an answer here:
C program printing weird characters
(1 answer)
Closed 8 years ago.
I have written this simple program for an assignment, but when I input my text, the output gives me symbols instead of chars. any help would be appreciated. I do not know why my output appears that way, but the program seems to compile fine. Maybe it is working and I need to just do a base test with the math to see if it is functioning properly. In any event if anyone sees errors in this, feedback is much appreciated.
#include <stdio.h>
#include <cs50.h>
#include <stdlib.h>
#include <ctype.h>
string Crypto(string, int); // rotation
int main(int argc, string argv[])
{
int k = 0;
// error checing
if (argc == 0 || argc == 1 || argc > 2)
{
// get mad
printf("Enter 1 integer as an argument. Stop messing around!\n Try Again: ");
return 1;
}
else
{
//create command line arguments to be stored into k
k = atoi(argv[1]);
k = k * 1;
}
// Get text to be encrypted
printf("Enter the text you want to encrypt: \n");
string a = GetString();
string b = Crypto(a, k);
printf("%s\n", b);
return 0;
}
//Now let's get cryptic
string
Crypto(string a, int k)
{
int c = 0;
for (int i = 0, n = strlen(a); i < n; i++)
{
if(a[i] >= 65 && a[i] <= 90)
{
c = ((26 - (91 - a[i] + k) % 26));
a[i] = c + 'A';
}
else
{
c = ((26 - (123 - a[i] + k % 26)));
a[i] = c + 'a';
}
}
return a;
}
In function Crypto, you need to attach a \0 (null) character to signify the end of the string. Just before return a;, write a a[i+1] = '\0'; statement.

Pi spigot, implemented in C, segfaults when number of digits is too high [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 8 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
I have made an implementation of a spigot algorithm in C, however, it segfaults (SIGSEGV) when the number of decimals to calculate is too high. The number of digits the error occurs at is slightly different on a few different windows computers I have, but it happens around 156210. I would give only the relevant code, but I honestly don't really understand the error, so I will give you my full code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int held[20]; //I wont have 19 consecutive 9's in pi, right?
int held_length = sizeof(held)/sizeof(int);
FILE *f;
void releaseDigits() {
int c;
for(c = held_length-1; c >= 0; c--) {
if(held[c] != -1) {
//printf("release: %i\n", held[c]); //debugging output
fprintf(f, "%i", held[c]);
}
}
}
void incHeld() {
int c;
for(c = held_length-1; c >= 0; c--) {
if(held[c] != -1) {
held[c]++;
}
}
}
void blankHeld() {
int c;
for(c = held_length-1; c >= 0; c--) {
held[c] = -1;
}
/*for(c = 0; c < held_length; c++) {
printf("BLANK_%i:%i\n", c, held[c]);
}*/ //debugging output
}
void deleteLast() {
int c = held_length-1;
while(held[c] != -1) {
c--;
}
held[c+1] = -1;
}
void holdDigit(int hold) {
int c = held_length-1;
while(held[c] != -1) {
c--;
}
held[c] = hold;
for(c = 0; c < held_length; c++) {
//printf("held_%i:%i\n", c, held[c]); //debugging output
}
}
void main() {
time_t start, end;
int n; //decimals of pi, 156207 max if printf, 156210 if fprintf, higher = sivsegv
printf("Decimal places of pi to calculate (max 156210 for now): ");
scanf("%i", &n);
start = clock();
f = fopen("pi.txt", "w"); //open file
if (f == NULL) {
printf("Error opening file!\n");
exit(1);
}
n++; //overcompensate for odd ending digit error
//initial array of 2,2,2,...2
int rem[((10*n)/3)+2]; //sizeof(one)/sizeof(int);
int init_count;
for(init_count = 0; init_count < ((10*n)/3)+2; init_count++) {
rem[init_count] = 2;
}
//main digit loop
int carry;
int decimal;
int pi_digit;
for(decimal = 0; decimal <= n; decimal++) {
carry = 0;
int sum;
int i;
for(i = (10*n)/3 + 1; i >= 1; i--) {
sum = (rem[i]*10)+carry;
rem[i] = sum % ((2*i)+1);
carry = ((sum-rem[i])/((2*i)+1))* i;
//printf("decimal:%i i:%i B:%i carry:%i sum:%i rem:%i\n", decimal, i, (2*i)+1, carry, sum, rem[i]); //debugging output
}
sum = (rem[0]*10)+carry;
rem[0] = sum % 10;
pi_digit = (sum - rem[0])/10;
//printf("sum:%i rem:%i\n",sum, rem[i]); //debugging output
if(pi_digit != 10) {
if(pi_digit != 9) {
if(decimal > 0) {
releaseDigits();
}
if(decimal == 1) {
fprintf(f, "."); //shove a point up in that shit
}
blankHeld();
holdDigit(pi_digit);
}
else {
holdDigit(pi_digit);
}
}
else {
incHeld();
releaseDigits();
blankHeld();
holdDigit(0);
}
printf("\r%i/%i decimal places done... ", decimal-1, n-1);
}
deleteLast(); //hide overcompensation
releaseDigits();
fclose(f);
end = clock();
int raw_seconds = (end - start)/1000.;
int seconds = raw_seconds % 60;
int minutes = (raw_seconds - seconds)/60;
printf("\n\nSuccessfully calculated %i decimal places of pi in %i minutes and %i seconds!\nSaved to pi.txt\nPress ENTER to exit the program.\n", n-1, minutes, seconds);
while(getch()!=0x0d);
}
What is happening here?
I used Valgrind, the famous memory checking tool, on your code. Relatively small values (i.e., 10, 100, 1000, even 10000) were no problem. Attempting 156210 instantly made Valgrind complain. It looks like the problem starts with this line:
int rem[((10*n)/3)+2];
The problem is that allocating storage in this manner asks for memory from the stack and this computed value ((10 * 156210 / 3 + 2) = 520702, sizeof(int) = 4 on Windows, so 520702 * 4 = about 2MB) is far more than the machine is prepared to give you from the stack.
If you need this much memory, better to allocate it from the heap using malloc() (don't forget to free() it afterwards).

Optimizing I/O(Output) in C code + a loop

I have a code which reads around (10^5) int(s) from stdin and then after performing ## i output them on stdout. I have taken care of the INPUT part by using "setvbuf" & reading lines using "fgets_unlocked()" and then parsing them to get the required int(s).
I have 2 issues which i am not able to come over with:
1.) As i am printing int(s) 5 million on stdout its taking lot of time : IS THERE ANY WAY TO REDUCE THIS( i tried using fwrite() but the o/p prints unprintable characters due to the reason using fread to read into int buffer)
2.) After parsing the input for the int(s) say 'x' i actually find the no of divisors by doing %(mod) for the no in a loop.(See in the code below): Maybe this is also a reason for my code being times out:
Any suggestions on this to improved.
Many thanks
This is actually a problem from http://www.codechef.com/problems/PD13
# include <stdio.h>
# define SIZE 32*1024
char buf[SIZE];
main(void)
{
int i=0,chk =0;
unsigned int j =0 ,div =0;
int a =0,num =0;
char ch;
setvbuf(stdin,(char*)NULL,_IOFBF,0);
scanf("%d",&chk);
while(getchar_unlocked() != '\n');
while((a = fread_unlocked(buf,1,SIZE,stdin)) >0)
{
for(i=0;i<a;i++)
{
if(buf[i] != '\n')
{
num = (buf[i] - '0')+(10*num);
}
else
if(buf[i] == '\n')
{
div = 1;
for(j=2;j<=(num/2);j++)
{
if((num%j) == 0) // Prob 2
{
div +=j;
}
}
num = 0;
printf("%d\n",div); // problem 1
}
}
}
return 0;
}
You can print far faster than printf.
Look into itoa(), or write your own simple function that converts integers to ascii very quickly.
Here's a quick-n-dirty version of itoa that should work fast for your purposes:
char* custom_itoa(int i)
{
static char output[24]; // 64-bit MAX_INT is 20 digits
char* p = &output[23];
for(*p--=0;i/=10;*p--=i%10+0x30);
return ++p;
}
note that this function has some serious built in limits, including:
it doesn't handle negative numbers
it doesn't currently handle numbers greater than 23-characters in decimal form.
it is inherently thread-dangerous. Do not attempt in a multi-threaded environment.
the return value will be corrupted as soon as the function is called again.
I wrote this purely for speed, not for safety or convenience.
Version 2 based on suggestion by #UmNyobe and #wildplasser(see above comments)
The code execution took 0.12 seconds and 3.2 MB of memory on the online judge.
I myself checked with 2*10^5 int(input) in the range from 1 to 5*10^5 and the execution took:
real 0m0.443s
user 0m0.408s
sys 0m0.024s
**Please see if some more optimization can be done.
enter code here
/** Solution for the sum of the proper divisor problem from codechef **/
/** # author dZONE **/
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
# include <error.h>
# define SIZE 200000
inline int readnum(void);
void count(int num);
int pft[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709};
unsigned long long int sum[SIZE];
int k = 0;
inline int readnum(void)
{
int num = 0;
char ch;
while((ch = getchar_unlocked()) != '\n')
{
if(ch >=48 && ch <=57)
{
num = ch -'0' + 10*num;
}
}
if(num ==0)
{
return -1;
}
return num;
}
void count(int num)
{
unsigned int i = 0;
unsigned long long tmp =0,pfac =1;
int flag = 0;
tmp = num;
sum[k] = 1;
for(i=0;i<127;i++)
{
if((tmp % pft[i]) == 0)
{
flag =1; // For Prime numbers not in pft table
pfac =1;
while(tmp % pft[i] == 0)
{
tmp =tmp /pft[i];
pfac *= pft[i];
}
pfac *= pft[i];
sum[k] *= (pfac-1)/(pft[i]-1);
}
}
if(flag ==0)
{
sum[k] = 1;
++k;
return;
}
if(tmp != 1) // For numbers with some prime factors in the pft table+some prime > 705
{
sum[k] *=((tmp*tmp) -1)/(tmp -1);
}
sum[k] -=num;
++k;
return;
}
int main(void)
{
int i=0,terms =0,num = 0;
setvbuf(stdin,(char*)NULL,_IOFBF,0);
scanf("%d",&terms);
while(getchar_unlocked() != '\n');
while(terms--)
{
num = readnum();
if(num ==1)
{
continue;
}
if(num == -1)
{
perror("\n ERROR\n");
return 0;
}
count(num);
}
i =0;
while(i<k)
{
printf("%lld\n",sum[i]);
++i;
}
return 0;
}
//Prob 2 Is your biggesr issue right now.... You just want to find the number of divisors?
My first suggestion will be to cache your result to some degree... but this requires potentially twice the amount of storage you have at the beginning :/.
What you can do is generate a list of prime numbers before hand (using the sieve algorithm). It will be ideal to know the biggest number N in your list and generate all primes till his square root. Now for each number in your list, you want to find his representation as product of factors, ie
n = a1^p1 * a1^p2 *... *an^pn
Then the sum of divisors will be.
((a1^(p1+1) - 1)/(a1 - 1))*((a2^(p2+1) - 1)/(a2-1))*...*((an^(pn+1) - 1)/(an-1))
To understand you have (for n = 8) 1+ 2 + 4 + 8 = 15 = (16 - 1)/(2 - 1)
It will drastically improve the speed but integer factorization (what you are really doing) is really costly...
Edit:
In your link the maximum is 5000000 so you have at most 700 primes
Simple decomposition algorithm
void primedecomp(int number, const int* primetable, int* primecount,
int pos,int tablelen){
while(pos < tablelen && number % primetable[pos] !=0 )
pos++;
if(pos == tablelen)
return
while(number % primetable[pos] ==0 ){
number = number / primetable[pos];
primecount[pos]++;
}
//number has been modified
//too lazy to write a loop, so recursive call
primedecomp(number,primetable,primecount, pos+1,tablelen);
}
EDIT : rather than counting, compute a^(n+1) using primepow = a; primepow = a*primepow;
It will be much cleaner in C++ or java where you have hashmap. At the end
primecount contains the pi values I was talking about above.
Even if it looks scary, you will create the primetable only once. Now this algorithm
run in worst case in O(tablelen) which is O(square root(Nmax)). your initial
loop ran in O(Nmax).

Resources