Program to find the prime factorization - c

I wrote this code to find the prime factorization of a number. I just cannot figure out the last part. If x is entered as a double or float, the program should print an error message and terminate. How do I achieve this?
#include <stdio.h>
int main()
{
int x, i;
printf("Enter an integer: ");
scanf("%d", &x);
if (x <= 1)
{
return 1;
}
printf("The prime factorization of %d is ", x);
if (x > 1)
{
while (x % 2 == 0)
{
printf("2 ");
x = x / 2;
}
for (i = 3; i < 1009; i = i + 2)
{
while (x % i == 0)
{
printf("%d ", i);
x = x / i;
}
}
}
return 0;
}

Your starting point should cover all desired and undesired cases so you should take float number from a user, not int. Then, you should check whether whole decimal part of the number is 0. That is, if all of them equals 0, the user want to provide an int number instead of float.
First step is to declare a float number:
float y;
After, take its value from the user:
scanf("%f", &y);
Second step is to check whether it is int or float. There are many ways for this step. For example, I find roundf() function useful. It takes a float number and computes the nearest integer to this number. So if the nearest integer is the number itself then the number has to be int. Right?
if(roundf(y)!=y)
If you are sure it is an int, you can move onto the third step: convert float type to int type. It is called type-casting. This step is required for the remaining part of your program because in your algorithm you manipulate the number with int type so just convert it to int:
x = (int)y;
After adding the line above, you can use the rest of code which you typed. I give the whole program:
#include <stdio.h>
#include <math.h>
int main()
{
int x,i;
float y;
printf("Enter an integer: ");
scanf("%f", &y);
if(roundf(y)!=y){
printf("%f is not an integer!",y);
return 1;
}
else{
x = (int)y;
}
if (x <= 1)
{
printf("%d <= 1",x);
return 1;
}
else
{
printf("The prime factorization of %d is ", x);
while (x%2 == 0)
{
printf("2 ");
x = x / 2;
}
for ( i = 3; i < 1009; i = i + 2)
{
while (x%i == 0)
{
printf("%d ",i);
x = x / i;
}
}
}
return 0;
}

The use of scanf() is a bit tricky, I would avoid it to scan user generated input at almost all cost. But nevertheless here is a short overview for how to get the errors of scanf()
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(void)
{
int x, i, scanf_return;
printf("Enter an integer: ");
/* Reset "errno". Not necessary here, just in case. */
errno = 0;
/* scanf() returns a value in case of an error */
scanf_return = scanf("%d", &x);
/*
* scanf() returns "EOF" if it didn't find all what you wanted or
* and error happened.
* It sets "errno" to the value of the actual error. See manpage
* for all of the details.
*/
if (scanf_return == EOF) {
/*
* The error is connected to the stream, so we can differ between
* an error within scanf() and and error with the input stream
* (here: stdin)
*/
if (ferror(stdin)) {
fprintf(stderr, "Something went wrong while reading stdin: %s\n", strerror(errno));
exit(EXIT_FAILURE);
} else {
/* e.g. a conversion error, a float instead of an integer, letters
instead of a decimal number */
fprintf(stderr, "Something went wrong within scanf()\n");
exit(EXIT_FAILURE);
}
}
/*
* If no error occurred, the return holds the number of objects
* scanf() was able to read. We only need one, but it would throw an
* error if cannot find any objects, so the check is here for
* pedagogical reasons only.
*/
if (scanf_return != 1) {
fprintf(stderr, "Something went wrong within scanf(): wrong number of objects read.\n");
exit(EXIT_FAILURE);
}
if (x <= 1) {
fprintf(stderr, "Input must be larger than 1!\n");
exit(EXIT_FAILURE);
}
printf("The prime factorization of %d is ", x);
/* No need for that test, x is already larger than one at this point. */
/* if (x > 1) { */
while (x%2 == 0) {
printf("2 ");
x = x / 2;
}
for (i = 3; i < 1009; i = i + 2) {
while (x%i == 0) {
printf("%d ",i);
x = x / i;
}
}
/* } */
/* Make it pretty. */
putchar('\n');
exit(EXIT_SUCCESS);
}
Does it work?
$ ./stackoverflow_003
Enter an integer: 1234
The prime factorization of 1234 is 2 617
$ factor 1234
1234: 2 617
$ ./stackoverflow_003
Enter an integer: asd
Something went wrong within scanf(): wrong number of objects read.
$ ./stackoverflow_003
Enter an integer: 123.123
The prime factorization of 123 is 3 41
No, it does not work. Why not? If you ask scanf() to scan an integer it grabs all consecutive decimal digits (0-9) until there is no one left. The little qualifier "consecutive" is most likely the source of your problem: a floating point number with a fractional part has a decimal point and that is the point where scanf() assumes that the integer you wanted ended. Check:
$ ./stackoverflow_003
Enter an integer: .123
Something went wrong within scanf(): wrong number of objects read
How do you find out? #weather-vane gave one of many ways to do so: check if the next character after the integer is a period (or another decimal separator of your choice):
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
int main(void)
{
int x, i, scanf_return;
char c = -1;
printf("Enter an integer: ");
/* Reset "errno". Not necessary here, just in case. */
errno = 0;
/* scanf() returns a value in case of an error */
scanf_return = scanf("%d%c", &x, &c);
/*
* scanf() returns "EOF" if it didn't find all what you wanted or
* and error happened.
* It sets "errno" to the value of the actual error. See manpage
* for all of the details.
*/
if (scanf_return == EOF) {
/*
* The error is connected to the stream, so we can differ between
* an error within scanf() and and error with the input stream
* (here: stdin)
*/
if (ferror(stdin)) {
fprintf(stderr, "Something went wrong while reading stdin: %s\n", strerror(errno));
exit(EXIT_FAILURE);
} else {
/* e.g. a conversion error, a float instead of an integer, letters
instead of a decimal number */
fprintf(stderr, "Something went wrong within scanf()\n");
exit(EXIT_FAILURE);
}
}
/*
* If no error occurred, the return holds the number of objects
* scanf() was able to read. We can use this information now.
* If there is a period (actually any character) after the integer
* it returns 2 (assuming no error happened, of course)
*/
/* If no integer given, the following character ("%c") gets ignored. */
if (scanf_return == 0) {
fprintf(stderr, "Something went wrong within scanf(): no objects read.\n");
exit(EXIT_FAILURE);
}
/* Found two objects, check second one which is the character. */
if (scanf_return == 2) {
if (c == '.') {
fprintf(stderr, "Floating point numbers are not allowed.\n");
exit(EXIT_FAILURE);
}
}
if (x <= 1) {
fprintf(stderr, "Input must be larger than 1!\n");
exit(EXIT_FAILURE);
}
printf("The prime factorization of %d is ", x);
/* No need for that test, x is already larger than one at this point. */
/* if (x > 1) { */
while (x%2 == 0) {
printf("2 ");
x = x / 2;
}
for (i = 3; i < 1009; i = i + 2) {
while (x%i == 0) {
printf("%d ",i);
x = x / i;
}
}
/* } */
/* Make it pretty. */
putchar('\n');
exit(EXIT_SUCCESS);
}
Check:
$ ./stackoverflow_003
Enter an integer: 123
The prime factorization of 123 is 3 41
$ ./stackoverflow_003
Enter an integer: 123.123
Floating point numbers are not allowed.
$ ./stackoverflow_003
Enter an integer: .123
Something went wrong within scanf(): no objects read.
Looks good enough for me. With one little bug:
$ ./stackoverflow_003
Enter an integer: 123.
Floating point numbers are not allowed
But I think I can leave that as an exercise for the dear reader.

You can try this simple C99 implementation of Pollard Rho algorithm :
// Integer factorization in C language.
// Decompose a composite number into a product of smaller integers.
unsigned long long pollard_rho(const unsigned long long N) {
// Require : N is a composite number, not a square.
// Ensure : you already performed trial division up to 23.
// Option : change the timeout, change the rand function.
static const int timeout = 18;
static unsigned long long rand_val = 2994439072U;
rand_val = (rand_val * 1025416097U + 286824428U) % 4294967291LLU;
unsigned long long gcd = 1, a, b, c, i = 0, j = 1, x = 1, y = 1 + rand_val % (N - 1);
for (; gcd == 1; ++i) {
if (i == j) {
if (j >> timeout)
break;
j <<= 1;
x = y; // "x" takes the previous value of "y" when "i" is a power of 2.
}
a = y, b = y; // computes y = f(y)
for (y = 0; a; a & 1 ? b >= N - y ? y -= N : 0, y += b : 0, a >>= 1, (c = b) >= N - b ? c -= N : 0, b += c);
y = (1 + y) % N; // function f performed f(y) = (y * y + 1) % N
for (a = y > x ? y - x : x - y, b = N; (a %= b) && (b %= a););
gcd = a | b; // the GCD(abs(y - x), N) was computed
// it continues until "gcd" is a non-trivial factor of N.
}
return gcd;
}
Usually you performed some trial division before calling the algorithm
The algorithm isn't designed to receive a prime number as input
Two consecutive calls may not result in the same answer
Alternately, there is a pure C quadratic sieve which factors numbers from 0 to 300-bit.
If in doubt about the primality of N you can use a C99 primality checker :
typedef unsigned long long int ulong;
ulong mul_mod(ulong a, ulong b, const ulong mod) {
ulong res = 0, c; // return (a * b) % mod, avoiding overflow errors while doing modular multiplication.
for (b %= mod; a; a & 1 ? b >= mod - res ? res -= mod : 0, res += b : 0, a >>= 1, (c = b) >= mod - b ? c -= mod : 0, b += c);
return res % mod;
}
ulong pow_mod(ulong n, ulong exp, const ulong mod) {
ulong res = 1; // return (n ^ exp) % mod
for (n %= mod; exp; exp & 1 ? res = mul_mod(res, n, mod) : 0, n = mul_mod(n, n, mod), exp >>= 1);
return res;
}
int is_prime(ulong N) {
// Perform a Miller-Rabin test, it should be a deterministic version.
const ulong n_primes = 9, primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23};
for (ulong i = 0; i < n_primes; ++i)
if (N % primes[i] == 0) return N == primes[i];
if (N < primes[n_primes - 1]) return 0;
int primality = 1, a = 0;
ulong b;
for (b = N - 1; ~b & 1; b >>= 1, ++a);
for (ulong i = 0; i < n_primes && primality; ++i) {
ulong c = pow_mod(primes[i], b, N);
if (c != 1) {
for (int j = a; j-- && (primality = c + 1 != N);)
c = mul_mod(c, c, N);
primality = !primality;
}
}
return primality;
}
To try it there is a factor function :
// return the number that was multiplied by itself to reach N.
ulong square_root(const ulong num) {
ulong res = 0, rem = num, a, b;
for (a = 1LLU << 62 ; a; a >>= 2) {
b = res + a;
res >>= 1;
if (rem >= b)
rem -= b, res += a;
}
return res;
}
ulong factor(ulong num){
const ulong root = square_root(num);
if (root * root == num) return root ;
const ulong n_primes = 9, primes[] = {2, 3, 5, 7, 11, 13, 17, 19, 23};
for (ulong i = 0; i < n_primes && primes[i] <= root; ++i)
if (num % primes[i] == 0) return primes[i];
if (is_prime(num))
return 1 ;
return pollard_rho(num);
}
Which is completed by the main function :
#include <assert.h>
int main(void){
for(ulong i = 2; i < 63; ++i){
ulong f = factor(i);
assert(f <= 1 || f >= i ? is_prime(i) : i % f == 0);
ulong j = (1LLU << i) - 1 ;
f = factor(j);
assert(f <= 1 || f >= j ? is_prime(j) : j % f == 0);
j = 1 | pow_mod((ulong) &main, i, -5);
f = factor(j);
assert(f <= 1 || f >= j ? is_prime(j) : j % f == 0);
}
}

There are some problems in your code:
you do not check the return value of scanf, so you cannot detect invalid or missing input and will have undefined behavior in those cases.
you only test divisors up to 1009, so composite numbers with larger prime factors do not produce any output.
prime numbers larger than 1009 do not produce any output.
you should probably output a newline after the factors.
Testing and reporting invalid input such as floating point numbers can be done more easily by reading the input as a full line and parsing it with strtol().
Here is a modified version:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
char input[120];
char ch;
char *p;
long x, i;
int last_errno;
printf("Enter an integer: ");
if (!fgets(input, sizeof input, stdin)) {
fprintf(stderr, "missing input\n");
return 1;
}
errno = 0;
x = strtol(input, &p, 0);
last_errno = errno;
if (p == input || sscanf(p, " %c", &ch) == 1) {
fprintf(stderr, "invalid input: %s", input);
return 1;
}
if (last_errno == ERANGE) {
fprintf(stderr, "number too large: %s", input);
return 1;
}
if (x < 0) {
fprintf(stderr, "number is negative: %ld\n", x);
return 1;
}
if (x <= 1) {
return 1;
}
printf("The prime factorization of %ld is", x);
while (x % 2 == 0) {
printf(" 2");
x = x / 2;
}
for (i = 3; x / i >= i;) {
if (x % i == 0) {
printf(" %ld", i);
x = x / i;
} else {
i = i + 2;
}
}
if (x > 1) {
printf(" %ld", x);
}
printf("\n");
return 0;
}

Related

finding how many times number2 is showing in number1

I am solving an exercise in C and I got stuck. I don't know the logic of the code to get to my solution. For example we enter 2 numbers from input let the numbers be 123451289 and 12 and I want to see how many times number 2 is showing at number 1 (if this is confusing let me know). For the numbers earlier the program outputs 2. I tried solving it here is my code:
#include <stdio.h>
int main() {
int num1, num2, counter = 0;
scanf("%d%d", num1, num2);
if (num1 < num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
int copy1 = num1;
int copy2 = num2;
while (copy2 > 0) {
counter++; // GETTING THE LENGHT OF THE SECOND NUMBER
copy2 /= 10;
// lastdigits = copy1 % counter //HERE I WANT TO GET THE LAST DIGITS OF THE FIRST NUMBER
// But it does not work
}
}
My question is how can I get the last digits of the first number according to the second one for example if the second number have 3 digits I want to get the last 3 digits of the first number. For the other part I think I can figure it out.
I must solve this problem WITHOUT USING ARRAYS.
The problem: find all the needles (e.g. 12) in a haystack (e.g. 123451289).
This can be done simply without arrays using a modulus of the needle. For 12, this is 100. That is, 12 is two digits wide. Using the modulus, we can
isolate the rightmost N digits of the haystack and compare them against the needle.
We "scan" haystack repeatedly by dividing by 10 until we reach zero.
Here is the code:
#include <stdio.h>
int
main(void)
{
int need, hay, counter = 0;
scanf(" %d %d", &hay, &need);
// ensure that the numbers are _not_ reversed
if (hay < need) {
int temp = need;
need = hay;
hay = temp;
}
// get modulus for needle (similar to number of digits)
int mod = 1;
for (int copy = need; copy != 0; copy /= 10)
mod *= 10;
// search haystack for occurences of needle
// examine the rightmost "mod" digits of haystack and check for match
// reduce haystack digit by digit
for (int copy = hay; copy != 0; copy /= 10) {
if ((copy % mod) == need)
++counter;
}
printf("%d appears in %d exactly %d times\n",need,hay,counter);
return 0;
}
UPDATE:
I'm afraid this does not work for 10 0. –
chqrlie
A one line fix for to the modulus calculation for the 10/0 case. But, I've had to add a special case for the 0/0 input.
Also, I've added a fix for negative numbers and allowed multiple lines of input:
#include <stdio.h>
int
main(void)
{
int need, hay, counter;
while (scanf(" %d %d", &hay, &need) == 2) {
counter = 0;
// we can scan for -12 in -1237812
if (hay < 0)
hay = -hay;
if (need < 0)
need = -need;
// ensure that the numbers are _not_ reversed
if (hay < need) {
int temp = need;
need = hay;
hay = temp;
}
// get modulus for needle (similar to number of digits)
int mod = need ? 1 : 10;
for (int copy = need; copy != 0; copy /= 10)
mod *= 10;
// search haystack for occurences of needle
// examine the rightmost "mod" digits of haystack and check for match
// reduce haystack digit by digit
for (int copy = hay; copy != 0; copy /= 10) {
if ((copy % mod) == need)
++counter;
}
// special case for 0/0 [yecch]
if ((hay == 0) && (need == 0))
counter = 1;
printf("%d appears in %d exactly %d times\n", need, hay, counter);
}
return 0;
}
Here is the program output:
12 appears in 123451289 exactly 2 times
0 appears in 10 exactly 1 times
0 appears in 0 exactly 1 times
UPDATE #2:
Good fixes, including tests for negative numbers... but I'm afraid large numbers still pose a problem, such as 2000000000 2000000000 and -2147483648 8 –
chqrlie
Since OP has already posted an answer, this is bit like beating a dead horse, but I'll take one last attempt.
I've changed from calculating a modulus of needle into calculating the number of digits in needle. This is similar to the approach of some of the other answers.
Then, the comparison is now done digit by digit from the right.
I've also switched to unsigned and allow for the number to be __int128 if desired/supported with a compile option.
I've added functions to decode and print numbers so it works even without libc support for 128 bit numbers.
I may be ignoring [yet] another edge case, but this is an academic problem (e.g. we can't use arrays) and my solution is to just use larger types for the numbers. If we could use arrays, we'd keep things as strings and this would be similar to using strstr.
Anyway, here's the code:
#include <stdio.h>
#ifndef NUM
#define NUM long long
#endif
typedef unsigned NUM num_t;
FILE *xfin;
int
numget(num_t *ret)
{
int chr;
num_t acc = 0;
int found = 0;
while (1) {
chr = fgetc(xfin);
if (chr == EOF)
break;
if ((chr == '\n') || (chr == ' ')) {
if (found)
break;
}
if ((chr >= '0') && (chr <= '9')) {
found = 1;
acc *= 10;
chr -= '0';
acc += chr;
}
}
*ret = acc;
return found;
}
#define STRMAX 16
#define STRLEN 100
const char *
numprt(num_t val)
{
static char strbuf[STRMAX][STRLEN];
static int stridx = 0;
int dig;
char *buf;
buf = strbuf[stridx++];
stridx %= STRMAX;
char *rhs = buf;
do {
if (val == 0) {
*rhs++ = '0';
break;
}
for (; val != 0; val /= 10, ++rhs) {
dig = val % 10;
*rhs = dig + '0';
}
} while (0);
*rhs = 0;
if (rhs > buf)
--rhs;
for (char *lhs = buf; lhs < rhs; ++lhs, --rhs) {
char tmp = *lhs;
*lhs = *rhs;
*rhs = tmp;
}
return buf;
}
int
main(int argc,char **argv)
{
num_t need, hay, counter;
--argc;
++argv;
if (argc > 0)
xfin = fopen(*argv,"r");
else
xfin = stdin;
while (1) {
if (! numget(&hay))
break;
if (! numget(&need))
break;
counter = 0;
// we can scan for -12 in -1237812
if (hay < 0)
hay = -hay;
if (need < 0)
need = -need;
// ensure that the numbers are _not_ reversed
if (hay < need) {
num_t temp = need;
need = hay;
hay = temp;
}
// get number of digits in needle (zero has one digit)
int ndig = 0;
for (num_t copy = need; copy != 0; copy /= 10)
ndig += 1;
if (ndig == 0)
ndig = 1;
// search haystack for occurences of needle
// starting from the right compare digit-by-digit
// "shift" haystack right on each iteration
num_t hay2 = hay;
for (; hay2 != 0; hay2 /= 10) {
num_t hcopy = hay2;
// do the rightmost ndig digits match in both numbers?
int idig = ndig;
int match = 0;
for (num_t need2 = need; idig != 0;
--idig, need2 /= 10, hcopy /= 10) {
// get single current digits from each number
int hdig = hcopy % 10;
int ndig = need2 % 10;
// do they match
match = (hdig == ndig);
if (! match)
break;
}
counter += match;
}
// special case for 0/0 et. al. [yecch]
if (hay == need)
counter = 1;
printf("%s appears in %s exactly %s times\n",
numprt(need), numprt(hay), numprt(counter));
}
return 0;
}
Here's the program output:
12 appears in 123451289 exactly 2 times
123 appears in 123451289 exactly 1 times
1234 appears in 123451289 exactly 1 times
1 appears in 123451289 exactly 2 times
0 appears in 10 exactly 1 times
0 appears in 0 exactly 1 times
1000000000 appears in 1000000000 exactly 1 times
2000000000 appears in 2000000000 exactly 1 times
This looks along the lines of what you're attempting.
You can use the pow() function from math.h to raise 10 to the power of how many digits you need for your modulus operation.
Compile with -lm or make your own function to calculate 10^num_digits
#include <stdio.h>
#include <math.h>
int main() {
int x = 123456789;
double num_digits = 3.0;
int last_digits = x % (int)pow(10.0, num_digits);
printf("x = %d\nLast %d Digits of x = %d\n", x, (int)num_digits, last_digits);
return 0;
}
Outputs:
x = 123456789
Last 3 Digits of x = 789
I think you are trying to ask :- if number1 = 1234567 and number2 = 673, then, length of number2 or number2 has 3 digits, so, you now want the last 3 digits in number1, i.e, '456', if I'm not wrong.
If that is the case, then, what you did to find the number of digits in num2 is correct, i.e,
while (copy2>0) {
counter++; // GETTING THE LENGHT OF THE SECOND NUMBER
copy2/=10;
}
you can do the same for number1 and find out its number of digits, then you can compare whether the number of digits in number2 is less than that in number1. Ex, 3 is less than number of digits in number1, so you can proceed further. Let's say number of digits in number1 is 7 and you want the last 3 digits, so you can do iterate over the digits in number1 till count of digits in number2 and pop out each last digit and store them in an array.
The code:
#include <stdio.h>
int main()
{
int num1,num2;
int count1 = 0, count2 = 0;
scanf("%d",&num1);
scanf("%d",&num2);
if(num1<num2){
int temp = num1;
num1 = num2;
num2 = temp;
}
int copy1 = num1;
int copy2 = num2;
while (copy1>0)
{
count1++;
copy1/=10;
}
while (copy2>0)
{
count2++;
copy2/=10;
}
// printf("num1 has %d digits and num2 has %d digits\n", count1, count2);
if (count1 >= count2)
{
int arr[count2];
int x = count2;
int p = num1;
int i = 0;
while (x > 0)
{
arr[i++] = p%10;
x --;
p/=10;
}
for (int j = 0; j < i; j++)
{
printf("%d ", arr[j]);
}
}
return 0;
}
output : 8 7 6
let's say, num1 = 12345678, num2 = 158, then arr = {8,7,6}.
You must determine the number of digits N of num2 and test if num1 ends with num2 modulo 10N.
Note these tricky issues:
you should not sort num1 and num2: If num2 is greater than num1, the count is obviously 0.
num2 has at least 1 digit even if it is 0.
if num1 and num2 are both 0, the count is 1.
if num2 is greater then INT_MAX / 10, the computation for mod would overflow, but there can only be one match, if num1 == num2.
it is unclear whether the count for 1111 11 should be 2 or 3. We will consider all matches, including overlapping ones.
to handle larger numbers, we shall use unsigned long long instead of int type.
Here is a modified version:
#include <limits.h>
#include <stdio.h>
int main() {
int counter = 0;
unsigned long long num1, num2;
if (scanf("%llu%llu", &num1, &num2) != 2) {
printf("invalid input\n");
return 1;
}
if (num1 == num2) {
/* special case for "0 0" */
counter = 1;
} else
if (num1 > num2 && num2 <= ULLONG_MAX / 10) {
unsigned long long copy1 = num1;
unsigned long long mod = 10;
while (mod < num2) {
mod *= 10;
}
while (copy1 > 0) {
if (copy1 % mod == num2)
counter++;
copy1 /= 10;
}
}
printf("count=%d\n", counter);
return 0;
}
Note that leading zeroes are not supported in either number: 101 01 should produce a count of 1 but after conversion by scanf(), the numbers are 101 and 1 leading to a count of 2. It is non trivial to handle leading zeroes as well as numbers larger than ULLONG_MAX without arrays.
This was the answer that i was looking for but thank you all for helping :)
#include <stdio.h>
#include <math.h>
int main(){
int num1,counter1,counter2,num2,temp,digit,copy1,copy2;
scanf("%d%d",&num1,&num2);
if(num1<num2){
temp = num1;
num1 = num2;
num2 = temp;
}
copy1 = num1;
copy2 = num2;
counter1 = counter2 = 0;
while (copy2>0) {
counter1++;
copy2/=10;
}
counter1 = pow(10,counter1);
if(num1> 1 && num2>1)
while (copy1>0) {
digit = copy1%counter1;
if(digit==num2){
counter2++;
}
copy1/=10;
} else{
if(num2<1){
while (copy1>0) {
digit = copy1%10;
if(digit==copy2){
counter2++;
}
copy1/=10;
}
}
}
printf("%d",counter2);
}

Reverse integer in c gives overflow

I am solving reverse integer problem in leetcode in c language.But it gives runtime error on line sum=sum+rem*10;.
runtime error: signed integer overflow: 964632435 * 10 cannot be represented in type 'int'
Here is the code.
#define INT_MAX 2147483647
#define INT_MIN -2147483648
int reverse(int x){
int sum=0,rem=0;
int p;
if(x > INT_MAX || x < INT_MIN){return 0;}
if(x==0){return 0;}
if(x<0){p=x;x=abs(x);}
while(x%10==0){x=x/10;}
while(x>0){
rem=x%10;
if(sum > INT_MAX || sum*(-1) < INT_MIN){return 0;}
sum=sum*10+rem;
x/=10;
}
if(p<0){sum=sum*(-1);return sum;}
else{return sum;}
}
One way - which isn't performance optimal but simple - is to convert the integer to a string and then revert the string and then convert back to integer.
The below solution is for positive integers - I'll leave it to OP to extend it to handle negative integers.
Could look like:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
int reverse(const int n)
{
if (n < 0)
{
printf("Handling of negative integers must be added\n");
exit(1);
}
char tmp1[100];
char tmp2[100] = { 0 };
sprintf(tmp1, "%d", n);
printf("Input : %s\n", tmp1);
size_t sz = strlen(tmp1);
for (size_t i = 0; i < sz; ++i)
{
tmp2[i] = tmp1[sz-i-1];
}
int result = tmp2[0] - '0';
char* p = tmp2+1;
while(*p)
{
if ((INT_MAX / 10) < result)
{
printf("oh dear: %d can't be reversed to int\n", n);
exit(1);
}
result = result * 10;
if ((INT_MAX - (*p - '0')) < result)
{
printf("oh dear: %d can't be reversed to int\n", n);
exit(1);
}
result += *p - '0';
p++;
}
return result;
}
int main()
{
printf("Output: %d\n", reverse(123));
printf("Output: %d\n", reverse(123456789));
printf("Output: %d\n", reverse(1234567899));
return 0;
}
Output:
Input : 123
Output: 321
Input : 123456789
Output: 987654321
Input : 1234567899
oh dear: 1234567899 can't be reversed to int
But it gives runtime error on line sum=sum+rem*10;.
To test for potential int overflow of positive sum, rem, compare against INT_MAX/10 and INT_MAX%10 beforehand.
if (sum >= INT_MAX / 10 && (sum > INT_MAX / 10 || rem > INT_MAX % 10)) {
// overflow
} else {
sum = sum * 10 + rem;
}
Handling negatives
Watch out for x = INT_MIN ... x = -x;. That is int overflow and undefined behavior.
Sometimes it is fun to solve such int problems of positive and negative numbers by converting the positive numbers to negative ones embrace the dark side - its your only hope. (maniacal laughter)
There are more int values less than zero than there are int values more than zero - by one. So x = -x is always well defined when x > 0.
// C99 or later code
#include <limits.h>
int reverse(int x) {
int x0 = x;
if (x0 > 0) {
x = -x; // make positive values negative, embrace the dark side
}
int reversed = 0;
while (x < 0) {
int rem = x % 10;
x /= 10;
if (reversed <= INT_MIN / 10
&& (reversed < INT_MIN / 10 || rem < INT_MIN % 10)) {
// overflow
return 0;
}
reversed = reversed * 10 + rem;
}
if (x0 > 0) {
if (reversed < -INT_MAX) {
// overflow
return 0;
}
reversed = -reversed;
}
return reversed;
}
Test code
#include <stdio.h>
int main() {
int x[] = {0, 1, -1, 42, 123456789, INT_MAX/10*10+1, INT_MIN/10*10-1,INT_MAX, INT_MIN};
size_t n = sizeof x / sizeof x[0];
for (size_t i = 0; i < n; i++) {
printf("Attempting to reverse %11d ", x[i]);
printf("Result %11d\n", reverse(x[i]));
}
}
Sample output
Attempting to reverse 0 Result 0
Attempting to reverse 1 Result 1
Attempting to reverse -1 Result -1
Attempting to reverse 42 Result 24
Attempting to reverse 123456789 Result 987654321
Attempting to reverse 2147483641 Result 1463847412
Attempting to reverse -2147483641 Result -1463847412
Attempting to reverse 2147483647 Result 0
Attempting to reverse -2147483648 Result 0
First, you should not be defining your own values for INT_MAX and INT_MIN. You should instead #include <limits.h> which defines these value.
Second, this:
sum > INT_MAX
Will never be true because sum can never hold a value larger than INT_MAX. So you can't perform an operation and then check afterward if it overflowed. What you can do instead is check the operation first and do some algebra that prevents overflow.
if ( INT_MAX / 10 < sum) return 0;
sum *= 10;
if ( INT_MAX - rem < sum) return 0;
sum += rem;

Understanding calling one function inside another C

I'd like to ask the following misunderstandings of C language, which I see I'm having.
I'm sorry if the code is not properly indented, I tried as much as I could but there are not so many guides on the internet.
The program asked given a starting number 'val' and a Even-Odd or Odd-Even alternating sequence (which stops whenever this rules is violated) to print the greater prime number with 'val'.
I tried with two functions and the main: one to control the GCD between two given numbers and the other to keep tracks of the greatest one, but I think I miss something in the code or in the conception of C function,
Because when compiled it returns me 0 or great number which I'm not entering.
One example to understand what I should do:
If my sequence was 10, 7, 8, 23 and my val was 3, I had to print 23, because it is the greatest integer prime with 3.
Here's the code :
#include <stdio.h>
int mcd(int a, int b)
{ // Gcd function
if (a == 0)
return b;
else
return mcd(b % a, b);
}
int valuta(int val, int h) // Valuing Max function
{
int temp = 0;
if (mcd(val, h) == 1 && h > temp)
temp = h;
return temp;
}
int main()
{
int val, d, x, y, z, t, contatore = 1;
scanf("%d", &val);
scanf("%d%d", &x, &y);
if (x > y && mcd(val, x) == 1)
{ // Two options
t = x;
}
else if (y > x && mcd(val, y) == 1)
{
t = y;
}
if ((x % 2 == 0 && y % 2 == 0) || (x % 2 == 1 && y % 2 == 1))
{ // Bad case
if (x > y && mcd(val, x) == 1)
{
t = x;
contatore = 0;
}
else if (y > x && mcd(val, y) == 1)
{
t = y;
contatore = 0;
}
}
else
{
while (contatore == 1)
{
scanf("%d", &z);
t = valuta(val, z);
if (x % 2 == 0 && z % 2 == 0)
{ // Even- Odd - Even
scanf("%d", &d);
t = valuta(val, d);
if (d % 2 == 0)
{
contatore = 0;
}
else
{
contatore = 0;
}
}
if (x % 2 == 1 && z % 2 == 1)
{ //Odd- Even- Odd
scanf("%d", &d);
t = valuta(val, d);
if (d % 2 == 1)
{
contatore = 0;
}
else
{
contatore = 0;
}
}
}
}
printf("%d\n", t);
return 0;
}
PS. Is there any way to reduce the number of lines of code or to reduce the effort in coding? I mean, a straightforward solution will be helpful.
Your valuta() function is flawed in that it needs to return the maximum qualifying value so far but has no knowledge of the previous maximum - temp is always zero. The following takes the previous maximum as an argument:
int valuta(int val, int h, int previous )
{
return ( mcd(val, h) == 1 && h > previous ) ? h : previous ;
}
And is called from main() thus:
t = valuta( val, x, t ) ;
The test mcd(val, h) == 1 is flawed, because mcd() only ever returns the value of parameter b which is not modified in the recursion, so will never return 1, unless the argument b is 1. Since I have no real idea what mcd() is intended to do, I cannot tell you how to fix it. It appear to be a broken implementation of Euclid's greatest common divisor algorithm, which correctly implemented would be:
int mcd(int a, int b)
{
if(b == 0)
return a;
else
return mcd(b, a % b);
}
But I cannot see how that relates to:
"[...] he greatest integer prime with 3 [...]
The odd/even even/odd sequence handling can be drastically simplified to the extent that it is shorter and simpler than your method (as requested) - and so that it works!
The following is a clearer starting point, but may not be a solution since it is unclear what it is it is supposed to do.
#include <stdio.h>
#include <stdbool.h>
int mcd(int a, int b)
{
if(b == 0)
return a;
else
return mcd(b, a % b);
}
int valuta(int val, int h, int previous )
{
return ( mcd(val, h) && h > previous ) ? h : previous ;
}
int main()
{
int val, x, t ;
printf( "Enter value:") ;
scanf("%d", &val);
typedef enum
{
EVEN = 0,
ODD = 1,
UNDEFINED
} eOddEven ;
eOddEven expect = UNDEFINED ;
bool sequence_valid = true ;
printf( "Enter sequence in odd/even or even/odd order (break sequence to exit):\n") ;
while( sequence_valid )
{
scanf("%d", &x);
if( expect == UNDEFINED )
{
// Sequence order determined by first value
expect = (x & 1) == 0 ? EVEN : ODD ;
}
else
{
// Switch expected odd/even
expect = (expect == ODD) ? EVEN : ODD ;
// Is new value in the expected sequence?
sequence_valid = (expect == ((x & 1) == 0 ? EVEN : ODD)) ;
}
// If the sequence is valid...
if( sequence_valid )
{
// Test if input is largest qualifying value
t = valuta( val, x, t ) ;
}
}
// Result
printf("Result: %d\n", t);
return 0;
}

Prime factorization of larger numbers than int

This program does Prime Factorization Of Numbers In C.
#include <stdio.h>
int main(void) {
int number, i, p, n, factors, count;
int numbers[1000000];
int counter = 0;
char text[100000];
for (count = 0; count < 1000000; count++) {
fgets(text, 10000000, stdin);
if (sscanf(text, "%d", &number) == 1) {
if (number == 0)
break;
numbers[count] = number;
} else {
numbers[count] = 0;
}
}
counter = 0;
for (i = 0; i < count; i++) {
if ((numbers[i] < 0) || (numbers[i] == 0)) {
fprintf(stderr, "Error: Wrong Input!\n");
return 100;
break;
}
number = numbers[i];
printf("Prime factorization of nubmer %d is:\n", number);
factors = 0;
for (p = 2; p * p <= number; p += 1 + (p & 1)) {
if (number % p == 0) {
n = 0;
factors++;
do {
number /= p;
n++;
} while (number % p == 0);
if (n == 1) {
printf("%d ", p);
++counter;
} else
printf("%d^%d ", p, n);
++counter;
if (count > 0 && number != 1)
printf("x ");
}
}
if (factors == 0 || number != 1)
printf("%d", number);
printf("\n");
}
return 0;
}
This program works fine for numbers smaller than 108. But my question is, if there is a way to make this program even for numbers like 1012. I know that int would not be enough, but when I tried for example long int, it didn't worked. Also I heard something about malloc, but I keep failing to implement (understand) it.
Factorising large numbers usually needs a more subtle approach than simple trial division. Here is a possible outline method:
Make a list of all the primes up to, say, 25,000.
Use the list to remove all prime factors below 25,000.
If there is a remainder > 1 then check if the remainder is prime with a Miller-Rabin test or similar.
If the remainder is prime, then you have found the last factor.
If the remainder is not prime, then you are going to have to factorise it. That will inevitably be slow I'm afraid.
You can use long long. But probably, the real problem is, that it will take a veeeeerrrryyy long time to do the factorization on numbers, that don't fit in a normal int. E.g. you're trying to factorize a prime number in the range 10^12, then you will have to do about 10^6 divisions.
The thing about malloc won't help you with this problem at all, because even bigger values will take even longer to factorize. So, if you want to know, how malloc works, I suggest opening a separate question for that.
Below is a rework of the code using unsigned long long. (I tossed the file stuff to keep this to a minimal example.) Whether this works for your purpose depends on how your system defines a long long (on my system it's 64 bits). I also redid the output format to be compatible with the Unix dc command's postfix notation so I could easily check if the results were correct:
#include <stdio.h>
#include <stdlib.h>
int main() {
unsigned long long large = 18446744073709551615ULL; // 2^64 - 1
for (unsigned long long counter = large - 1000; counter < large; counter++) {
unsigned long long number = counter;
printf("Prime factorization of %llu is:", number);
unsigned long factors = 0;
for (unsigned long long p = 2; p * p <= number; p += 1 + (p & 1)) {
if (number % p == 0) {
factors++;
unsigned long n = 0;
do {
number /= p;
n++;
} while (number % p == 0);
if (n == 1) {
printf(" %llu", p);
}
else {
printf(" %llu %lu ^", p, n);
}
if (number != 1 && factors > 1) {
printf(" *");
}
}
}
if (factors == 0 || number != 1) {
factors++;
printf(" %llu", number);
}
if (factors > 1) {
printf(" *");
}
printf("\n");
}
return 0;
}
SAMPLE OUTPUT
% ./a.out
Prime factorization of 18446744073709550615 is: 5 563 * 751 * 8725722280871 *
Prime factorization of 18446744073709550616 is: 2 3 ^ 3 * 41 * 7523 * 8243 * 14479 * 20879 *
Prime factorization of 18446744073709550617 is: 79 557 * 419215600611539 *
Prime factorization of 18446744073709550618 is: 2 2298974999 * 4011949691 *
Prime factorization of 18446744073709550619 is: 3 3 ^ 1008659 * 677347590683 *
Prime factorization of 18446744073709550620 is: 2 2 ^ 5 * 7 * 149 * 233 * 3795329598449 *
Prime factorization of 18446744073709550621 is: 11 23 * 72912031911895457 *
Prime factorization of 18446744073709550622 is: 2 3 * 479909 * 6406334004193 *
Prime factorization of 18446744073709550623 is: 3421377637 5391612979 *
Prime factorization of 18446744073709550624 is: 2 5 ^ 61 * 593 * 1699 * 9379762391 *
Prime factorization of 18446744073709550625 is: 3 5 4 ^ * 13 * 756789500459879 *
Prime factorization of 18446744073709550626 is: 2 3743461 * 2463862195133 *
Prime factorization of 18446744073709550627 is: 7 1283 * 4339 * 627089 * 754877 *
Prime factorization of 18446744073709550628 is: 2 2 ^ 3 2 ^ * 101 * 293 * 42751 * 405025111 *
Prime factorization of 18446744073709550629 is: 17 43 * 613 * 66457 * 619442699 *
...
This runs slower but reasonably. You can push this further on some systems by swapping unsigned long long for a uint128_t which some compilers support somewhat:
typedef unsigned __int128 uint128_t;
(And up the unsigned long declarations to unsigned long long.) You'd need to supply number printing routines for the uint128_t type as printf() isn't going to handle them directly. I tried this with the above code and it worked:
Prime factorization of 340282366920938463426481119284349108124 is: 2 2 ^ 31 * 6131 * 7654271 * 21163829 * 21491837 * 128562653437 *
% dc
2 2 ^ 31 * 6131 * 7654271 * 21163829 * 21491837 * 128562653437 * p
340282366920938463426481119284349108124
But I never saw it complete more than one number while running it!
Using type unsigned long long for number and the prime factors will take you to 1019 at the price of longer computation times.
Note however that defining a large local array with automatic storage may cause problems, especially when it reaches a size of 8 megabytes as would be the case for type unsigned long long (this type is at least 64-bit wide). Allocating it from the heap is safer.
Here is an adapted version of the code:
#include <stdio.h>
#include <stdlib.h>
#define NUMBER_MAX 1000000
int main(void) {
unsigned long long *numbers;
unsigned long long number, p;
int i, n, factors, count;
char text[100];
numbers = calloc(NUMBER_MAX, sizeof(*numbers));
if (numbers == NULL) {
printf("cannot allocate number array\n");
return 1;
}
for (count = 0; count < NUMBER_MAX; count++) {
if (!fgets(text, sizeof text, stdin)) {
break;
}
if (sscanf(text, "%llu", &number) == 1 && number > 0) {
numbers[count] = number;
} else {
fprintf(stderr, "Error: Wrong Input!\n");
return 100;
}
}
for (i = 0; i < count; i++) {
number = numbers[i];
printf("Prime factorization of nubmer %llu is:\n", number);
factors = 0;
for (p = 2; p < 0x100000000 && p * p <= number; p += 1 + (p & 1)) {
if (number % p == 0) {
n = 0;
factors++;
do {
number /= p;
n++;
} while (number % p == 0);
if (n == 1) {
printf("%llu ", p);
} else {
printf("%llu^%d ", p, n);
}
if (number != 1) {
printf("* ");
}
}
}
if (factors == 0 || number != 1) {
printf("%llu", number);
}
printf("\n");
}
free(numbers);
return 0;
}

Extracting individual digits from a long in C

I'm doing a homework assignment for my course in C (first programming course).
Part of the assignment is to write code so that a user inputs a number up to 9 digits long, and the program needs to determine whether this number is "increasing"/"truly increasing"/"decreasing"/"truly decreasing"/"increasing and decreasing"/"truly decreasing and truly increasing"/"not decreasing and not increasing". (7 options in total)
Since this is our first assignment we're not allowed to use anything besides what was taught in class:
do-while, for, while loops, else-if, if,
break,continue
scanf, printf ,modulo, and the basic operators
(We can't use any library besides for stdio.h)
That's it. I can't use arrays or getchar or any of that stuff. The only function I can use to receive input from the user is scanf.
So far I've already written the algorithm with a flowchart and everything, but I need to separate the user's input into it's distinct digits.
For example, if the user inputs "1234..." i want to save 1 in a, 2 in b, and so on, and then make comparisons between all the digits to determine for example whether they are all equal (increasing and decreasing) or whether a > b >c ... (decreasing) and so on.
I know how to separate each digit by using the % and / operator, but I can't figure out how to "save" these values in a variable that I can later use for the comparisons.
This is what I have so far:
printf("Enter a positive number : ");
do {
scanf ("%ld", &number);
if (number < 0) {
printf ("invalid input...enter a positive integer: ");
continue;
}
else break;
} while (1);
while (number < 0) {
a = number % 10;
number = number - a;
number = number / 10;
b = a;
}
Why not scan them as characters (string)? Then you can access them via an array offset, by subtracting the offset of 48 from the ASCII character code. You can verify that the character is a digit using isdigit from ctype.h.
EDIT
Because of the incredibly absent-minded limitations that your professor put in place:
#include <stdio.h>
int main()
{
int number;
printf("Enter a positive number: ");
do
{
scanf ("%ld", &number);
if (number < 0)
{
printf ("invalid input...enter a positive integer: ");
continue;
}
else break;
} while (1);
int a = -1;
int b = -1;
int c = -1;
int d = -1;
int e = -1;
int f = -1;
int g = -1;
int h = -1;
int i = -1;
while (number > 0)
{
if (a < 0) a = number % 10;
else if (b < 0) b = number % 10;
else if (c < 0) c = number % 10;
else if (d < 0) d = number % 10;
else if (e < 0) e = number % 10;
else if (f < 0) f = number % 10;
else if (g < 0) g = number % 10;
else if (h < 0) h = number % 10;
else if (i < 0) i = number % 10;
number /= 10;
}
/* Printing for verification. */
printf("%i", a);
printf("%i", b);
printf("%i", c);
printf("%i", d);
printf("%i", e);
printf("%i", f);
printf("%i", g);
printf("%i", h);
printf("%i", i);
return 0;
}
The valid numbers at the end will be positive, so those are the ones you validate to meet your different conditions.
Since you only need to compare consecutive digits, there is an elegant way to do this without arrays:
int decreasing = 2;
int increasing = 2;
while(number > 9)
{
int a = number % 10;
int b = (number / 10) % 10;
if(a == b)
{
decreasing = min(1, decreasing);
increasing = min(1, increasing);
}
else if(a > b)
decreasing = 0;
else if(a < b)
increasing = 0;
number /= 10;
}
Here, we walk through the number (by dividing by 10) until only one digit remains. We store info about the number up to this point in decreasing and increasing - a 2 means truly increasing/decreasing, a 1 means increasing/decreasing, and a 0 means not increasing/decreasing.
At each step, a is the ones digit and b is the tens. Then, we change increasing and decreasing based on a comparison between a and b.
At the end, it should be easy to turn the values of increasing and decreasing into the final answer you want.
Note: The function min returns the smaller of its 2 arguments. You should be able to write your own, or replace those lines with if statements or conditionals.
It's stupid to ask you to do loops without arrays --- but that's your teacher's fault, not yours.
That being said, I would do something like this:
char c;
while (1) {
scanf("%c", &c);
if (c == '\n') /* encountered newline (end of input) */
break;
if (c < '0' || c > '9')
break; /* do something to handle bad characters? */
c -= '0';
/*
* At this point you've got 0 <= c < 9. This is
* where you do your homework :)
*/
}
The trick here is that when you type numbers into a program, you send the buffer all at once, not one character at a time. That means the first scanf will block until the entire string (i.e. "123823" or whatever) arrives all at once, along with the newline character ( '\n' ). Then this loop parses that string at its leisure.
Edit For testing the increasing/decreasing-ness of the digits, you may think you need to store the entire string, but that's not true. Just define some additional variables to remember the important information, such as:
int largest_digit_ive_seen, smallest_digit_ive_seen, strict_increasing_thus_far;
etc. etc.
Let us suppose you have this number 23654
23654 % 10000 = 2 and 3654
3654 % 1000 = 3 and 654
654 % 100 = 6 and 54
54 % 10 = 5 and 4
4
This way you can get all the digits. Of course, you have to know if the number is greater than 10000, 1000, 100 or 10, in order to know the first divisor.
Play with sizeof to get the size of the integer, in order to avoid a huge if...else statement
EDIT:
Let us see
if (number>0) {
// Well, whe have the first and only digit
} else if (number>10) {
int first_digit = number/10;
int second_digit = number % 10;
} else if (number>100) {
int first_digit = number/100;
int second_digit = (number % 100)/10;
int third_digit = (number % 100) % 10;
} ...
and so on, I suppose
// u_i is the user input, My homework asked me to extract a long long, however, this should also be effective for a long.
int digits = 0;
long long d_base = 1;
int d_arr[20];
while (u_i / d_base > 0)
{
d_arr[digits] = (u_i - u_i / (d_base * 10) * (d_base * 10)) / d_base;
u_i -= d_arr[digits] * d_base;
d_base *= 10;
digits++;
}
EDIT: the extracted individual digit now lives in the int array d_arr. I'm not good at C, so I think the array declaration can be optimized.
Here's a working example in plain C :
#include <stdio.h>
unsigned long alePow (unsigned long int x, unsigned long int y);
int main( int argc, const char* argv[] )
{
int enter_num, temp_num, sum = 0;
int divisor, digit, count = 0;
printf("Please enter number\n");
scanf("%d", &enter_num);
temp_num = enter_num;
// Counting the number of digits in the entered integer
while (temp_num != 0)
{
temp_num = temp_num/10;
count++;
}
temp_num = enter_num;
// Extracting the digits
printf("Individual digits in the entered number are ");
do
{
divisor = (int)(alePow(10.0, --count));
digit = temp_num / divisor;
temp_num = temp_num % divisor;
printf(" %d",digit);
sum = sum + digit;
}
while(count != 0);
printf("\nSum of the digits is = %d\n",sum);
return 0;
}
unsigned long alePow(unsigned long int x, unsigned long int y) {
if (x==0) { return 0; }
if (y==0||x==1) { return 1; }
if (y==1) { return x; }
return alePow(x*x, y/2) * ((y%2==0) ? 1 : x);
}
I would suggest loop-unrolling.
int a=-1, b=-1, c=-1, d=-1, e=1, f=-1, g=-1, h=-1, i=-1; // for holding 9 digits
int count = 0; //for number of digits in the given number
if(number>0) {
i=number%10;
number/=10;
count++;
}
if(number>0) {
h=number%10;
number/=10;
count++;
}
if(number>0) {
g=number%10;
number/=10;
count++;
}
....
....
/* All the way down to the storing variable a */
Now, you know the number of digits (variable count) and they are stored in which of the variables. Now you have all digits and you can check their "decreasing", "increasing" etc with lots of if's !
I can't really think of a better soltion given all your conditions.

Resources