How to increase th range of integers in C? - c

I tried to solve the Small Factorial problem on SPOJ and got 'Wrong answer'. I wrote the following code :
#include <stdio.h>
int main() {
int t,i, num;
unsigned long long int fact=1;
scanf ("%d", &t);
while (t-- >0) {
fact=1;
scanf ("%d", &num);
for (i=num; i>0; i--) {
fact*=i;
}
printf ("%llu\n",fact);
}
return 0;
}
This code is not finding factorial for large inputs like 100. What are the changes required?

In C and C++ you have the maximum allowed range from -2^63+1 to +2^63-1 which is for long long data type. As you can see this range is still too small to store >20 digits.
You have to use a char array to store single digit per array index.
one way to do this in C++:
#include<stdio.h>
#include<iostream>
int main()
{
int t;
char a[200]; //array will have the capacity to store 200 digits.
int n,i,j,temp,m,x;
scanf("%d",&t); //enter total elements
while(t--)
{
scanf("%d",&n); // enter no. one at a time
a[0]=1; //initializes array with only 1 digit, the digit 1.
m=1; // initializes digit counter
temp = 0; //Initializes carry variable to 0.
for(i=1;i<=n;i++)
{
for(j=0;j<m;j++)
{
x = a[j]*i+temp; //x contains the digit by digit product
a[j]=x%10; //Contains the digit to store at position j
temp = x/10; //Contains the carry value that will be stored on later indeces
}
while(temp>0) //while loop that will store the carry value on array.
{
a[m]=temp%10;
temp = temp/10;
m++; // increments digit counter
}
}
for(i=m-1;i>=0;i--)
printf("%d",a[i]);
printf("\n");
}
return 0;
}

Related

C program to read 'n' numbers and find out the sum of odd valued digits of each number and print them

i am new to programing, i want to know that how we can find the odd digits in a number.
the condition in this program is we should only use concept of arrays.I tried a code for this as follows:
#include <stdio.h>
int main()
{
int A[50],i,x,y,n,sum=0;
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
for(i=0;i<n;i++){
x=A[i]%10;
if(x%2!=0)
sum=sum+x;
A[i]=A[i]/10;
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
but in this the code is checking for only one digit of the first number in the loop and then next time it is going to check the digit of second number.
so, i need to write a code to check all digits in the number and then it goes to next number and check all digits and should continue the same process in the loop.So, for this how should i modify my code?
You were missing a loop that would iterate through every digit of A[i] - the inner while loop below,
#include <stdio.h>
int main()
{
int A[50], i, x, y, n, sum=0;
printf("How many numbers will you input?\n");
scanf("%d",&n);
printf("the value is %d\n",n);
for(i=0; i<n; i++) {
scanf("%d",&A[i]);
}
for(i=0; i<n; i++) {
sum = 0;
while (A[i] > 0) {
x = A[i]%10;
if(x%2 != 0) {
sum = sum + x;
}
A[i] = A[i]/10;
}
printf("the sum of odd numbers is %d\n",sum);
}
return 0;
}
The exact algorithm for iterating through each digit in a nice form can be found in this post - although for a different language. Here, apart from the while loop, you also need to reset the sum each time unless you want a cumulative sum over all provided numbers.
Note that I changed the formatting a bit - more space, extra braces, and a message about what you're prompting the user to input.
int temp;
int sum = 0;
temp = number;
do {
lastDigit = temp % 10;
temp = temp / 10;
sum += (lastDigit %2 != 0) ? lastDigit : 0;
} while(temp > 0);

How to double digits in number

I am having a problem on how to double digits of any number.
For example, the number: 12345 output would be 1122334455 using functions and loops.
#include <stdio.h>
int main() {
int num;
printf("Please Enter a number");
scanf("%d",&num);
for(int i=0;i<=num%10;i++) {
if(i==num%10)
newNum+=i;
for(int i=1;i<=num%10;i++) {
if(i==num/10%10)
newNum+=i;
I am assuming that you do not have to store the value with duplicated digits, as storing it as int will quickly overflow. If you have to, you can use long long or an array.
Your for loop does not make sense. You have to loop until all intergers have been duplicated. To do so, determine the ones place with mod 10, then divide number by 10. It will loop until number is 0. Try this.
#include <stdio.h>
int main(void) {
int number;
int temp;
printf("Enter an integer: ");
scanf("%d", &number);
while(number) {
temp = number % 10;
printf("%d%d", temp, temp);
number /= 10;
}
return 0;
}

How to compare the digits of 2 integer numbers in c (without arrays and strings)

I am making simple example of little game about guessing numbers.
And I want to build a function which check the numbers and make two values as follows:
1) hits-the number of digits that contain in both number and in same place for both numbers.
2) misses-the number of the digits which contain in both number but not in the same place.
For example:
int systemNumber=1653;
int userGuess=5243;
in this example, in both numbers there are the digits 5 and 3. In both numbers the digit 3 in the same place. But, the digit 5 in systemNumber is not in the same place as userNumber. So, we have here 1 hit and 1 miss.
I've written the code for it with arrays, and I'd like to know if there is a way that I will be able to do this without array and strings.
Here is my code. Please, if you have any improvement for my code, I'd like to know it :)
#include <stdio.h>
#include <stdlib.h>
void checkUserCode(int num1[4], int num2[4]); // declare the function which check the guess
int hits=0, misses=0; // hits and misses in the guess
int main(void)
{
int userCode=0;
int userCodeArray[4];
int systemCodeArray[4]={1, 4, 6, 3};
int i=0;
// printing description
printf("welcome to the guessing game!\n");
printf("your goal is to guess what is the number of the system!\n");
printf("the number have 4 digits. Each digit can be between 1 to 6\nGood Luck!\n");
// input of user guess
printf("enter number: ");
scanf("%d", &userCode);
for (i=3; i>=0; i--)
{
userCodeArray[i]=userCode%10;
userCode=userCode/10;
}
checkUserCode(systemCodeArray, userCodeArray);
printf("there are %d hits and %d misess", hits, misses); // output
return 0;
}
/*
this function gets two arrays and check its elements
input (parameters): the two arrays (codes) to check
output (returning): number of hits and misses
if the element in one array also contains in the other array but not the same index: add a miss
if the element in one array also contains in the other array and they have the same index: add a hits
*/
void checkUserCode(int num1[4], int num2[4])
{
int i=0, j=0;
for (i=0; i<4; i++)
{
for (j=0; j<4; j++)
{
if(num1[i]==num2[j])
{
if (j==i)
hits++;
else
misses++;
}
}
}
}
Here is an example I wrote a while ago, which I tweaked for your problem:
I basically uses two for loops, the outer loop going over the first number, 1653, and the inner loop going over the second number, 5243. It basically compares each individual number in the first number against all the numbers in the second number.
Depending on the counters, it evaluates if equal numbers have been matched in the same positions, using modulo %10 to compare each number.
This is the code:
#include <stdio.h>
#include <stdlib.h>
int
main(void) {
int num1 = 1653;
int num2 = 5243;
int pos1, pos2, hit = 0, miss = 0, i, j;
pos1 = 0;
for (i = num1; i > 0; i /= 10) {
pos2 = 0;
for (j = num2; j > 0; j /= 10) {
if (i % 10 == j % 10) {
if (pos1 == pos2) {
hit++;
} else {
miss++;
}
}
pos2++;
}
pos1++;
}
printf("hits = %d\n", hit);
printf("misses = %d\n", miss);
return 0;
}

Calculating Size of the Array

I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.

Int array to store large numbers (over 20 digits)

I have an assignment that requires me to first set up integer arrays to store arbitrarily large numbers. By using each element of an int array, I can hold one digit per element because int variable types are 32 bits and can only reach up to about 2 billion before failing. I know that there are other libraries using BigInt but I wanted to make my own arrays instead.
I tested my code out, but it doesn't seem to be accepting values past 9 digits until it starts to fail.
int * toArray(int, int);
int main()
{
int n, *res, counter, i;
printf("Input: ");
scanf("%d", &n);
while(n>0){
n/=10;
counter++;
}
res = toArray(n, counter);
for(i=1;i<=counter;i++){
printf("%d", *(res)+i);
}
printf("\n");
}
int * toArray(int n, int counter)
{
int i;
int *numberArray = malloc(sizeof(int) * counter);
for(i=0; i< counter; i++)
{
numberArray[i] = n % 10;
}
return numberArray;
}
I want to be able to accept close to twenty digits at the very least. I know this can be done with int arrays, although char arrays (or strings) are also a possibility. But I wanted to use int arrays instead. Any help in understanding why it fails around 9 digits and suggestions for going past that would be very much appreciated. Thank you.
The problem is that you are reading an int from keyboard
scanf("%d", &n);
so therefore no matter how many digits you enter, you still will only get 9 digits.
In order to be able to enter an arbitrary number you would have to read it as a string instead, then convert it to your int array.
EDIT:
this way (for instance) would allow for 20 digits
char ch;
int digits[20];
int i = 0;
do
{
ch = fgetc(stdin);
if ( isdigit(ch) )
{
digits[i++] = ch - 48; // convert ASCII to int
}
}
while (isdigit(ch) && i < sizeof(digits)/sizeof(digits[0]));
#include<stdio.h>
#include<stdlib.h>
int *toArray(long long int n, int counter); int main() {
long long int n=0,copy_of_n=0;
int counter=0, i=0;
int *res=NULL;
printf("Input: ");
scanf("%lld", &n);//Refer note in the answer
copy_of_n=n;//see the while loop why use this.
while(n>0){
n/=10;//Good, but you are not storing it. copy_of_n does that.
counter++;//You didn't initialize this
}
res=toArray(copy_of_n, counter);
for(i=counter-1;i>=0;i--){//This ensures you get the numbers in a proper order and since index starts from 0 in the toArray function
printf("%d", res[i]);
}
printf("\n");
free(res);//You forgot this
return 0; }
int *toArray(long long int n, int counter) {
int i=0;
int *numberArray = malloc(sizeof(int) * counter);
memset(numberArray,0x00,counter*sizeof(int));//Good to do this
//Check for memory allocation
for(i=0; i< counter; i++)
{
numberArray[i] = n % 10;
n=n/10LL;//You have to remove the digits too
}
return numberArray; }
NOTE: Read in a while loop the integers in small parts because long long has limits of how many digits it can store. Another approach would be to store in a string and send split the string into exactly the max. no. of digits that can be stored in long long in the n variable and send it to the function, part by part.
long long size is implementation dependent, hence ensure you check the max. no. of digits it can accomodate.(It will ofcourse bypass your 9-digit limit as asked in question)

Resources