BTW I know that's not the most efficient way to do it but if I wanted to do it like I did, what did I do incorrectly? The task was: Given a five digit integer, print the sum of its digits.
Constraint: 10000 <= n <= 99999
Sample Input: 10564
Sample Output: 16
My code:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n, sum;
int remainder_array[4] = { n % 1000; n % 100, n % 10, n };
int digits_array[4];
scanf("%d", &n);
// Complete the code to calculate the sum of the five digits on n.
if (10000 <= n && n <= 99999) {
else if (remainder_array[0] = 0) {
digits_array[0] = (n - remainder_array[0]) / 1000;
n = remainder_array[1];
} else if (remainder_array[1] != 0) {
digits_array[1] = (n - remainder_array[1]) / 100;
n = remainder_array[2];
} else if (reminder_array[2] != 0) {
digits_array[2] = (n - remainder_array[2]) / 10;
n = remainder_array[3];
} else if (reminder_array[3] != 0) {
digits_array[3] = n - remainder_array[3];
} else {
printf("%d", n / 1000);
}
sum = digits_array[0] + digits_array[1] + digits_array[2] + digits_array[3];
printf("%d", sum);
}
return 0;
}
your algorithm is far too complicated, It can be done much easier way without arrays.
int sumof5LSD(int x)
{
int result = 0;
for(int digit = 1; digit <=5; digit++)
{
result += abs(x % 10);
x /= 10;
}
return result;
}
int main(void)
{
printf("SUM: %d", sumof5LSD(10564));
}
https://godbolt.org/z/bcdM8P
or if you are not allowed to use loops:
int sumof5LSD(int x)
{
int result = 0;
result += abs(x % 10);
x /= 10;
result += abs(x % 10);
x /= 10;
result += abs(x % 10);
x /= 10;
result += abs(x % 10);
x /= 10;
result += abs(x % 10);
return result;
}
It is good to use functions to perform similar tasks.
Version with scanf
int main(void)
{
int n;
scanf("%d", &n);
printf("SUM of 5 digits of %d = %d", n, sumof5LSD(n));
}
it will also calculate the sum of 5 digits of the negative number
There are multiple issues in your code:
you initialize remainder_array from the value of n before reading the value of n.
the initializer is incorrect: the separator should be ,, not ;.
you start the statement inside the if body with else, which is a syntax error.
the test if (remainder_array[0] = 0) sets remainder_array[0] to 0 and evaluates to false.
remainder_array is misspelt a reminder_array
Your approach is fine, but you should intialize remainder_array with the actual remainders (5 of them), after reading and checking n:
#include <stdio.h>
int main() {
int n;
if (scanf("%d", &n) == 1 && 10000 <= n && n <= 99999) {
int remainder_array[5] = { n / 10000, n / 1000 % 10, n / 100 % 10, n / 10 % 10, n % 10 };
int sum = remainder_array[0] + remainder_array[1] + remainder_array[2] +
remainder_array[3] + remainder_array[4];
printf("%d\n", sum);
}
return 0;
}
Note that you don't actually need this remainder_array, you could just write:
#include <stdio.h>
int main() {
int n;
if (scanf("%d", &n) == 1 && 10000 <= n && n <= 99999) {
int sum = n / 10000 + n / 1000 % 10 + n / 100 % 10 + n / 10 % 10 + n % 10;
printf("%d\n", sum);
}
return 0;
}
Here is a more readable and more generic version:
#include <stdio.h>
int main() {
int n;
if (scanf("%d", &n) == 1 && 10000 <= n && n <= 99999) {
int sum = 0;
while (n >= 10) {
sum += n % 10;
n = n / 10;
}
sum += n;
printf("%d\n", sum);
}
return 0;
}
Apart from the errors and modifications what #P_J_ and #chqrlie has mentioned I have noticed some major logical errors and misunderstanding of a basic concept in your code(assuming that first else if is replaced by if)
you have given else if statement repeatedly, now what this does is that whenever the first condition it encounters is true it executes the block inside and exits from the branch i.e remaining statements after else if is not executed, this might cause a major logical error in your program.
if (10000 <= n && n <= 99999) {
else if (remainder_array[0] = 0) {
digits_array[0] = (n - remainder_array[0]) / 1000;
n = remainder_array[1];
} else if (remainder_array[1] != 0) {
digits_array[1] = (n - remainder_array[1]) / 100;
n = remainder_array[2];
} else if (reminder_array[2] != 0) {
digits_array[2] = (n - remainder_array[2]) / 10;
n = remainder_array[3];
} else if (reminder_array[3] != 0) {
digits_array[3] = n - remainder_array[3];
} else {
printf("%d", n / 1000);
}
Now in this picture if you notice the output you can see that the digits_array[1-3] are 0 this is because of the reason mentioned above(it is zero cause I have initialized it beforehand) hence the sum is zero.
And the second logical error is that you are dividing a 5 digit number by 1000 this will give you thousand's place i.e in example 10546 this step will result in 10 this is wrong, take another example 12233 not the sum for the digits should result in 11 but you will get 20 because when you divide 12233 by 1000 the first value of digits_array (digit_array[0]) is 12 so the entire output goes wrong. so to correct this divide it by 10000 (only for this program statement as it has 5 digits).
But still, if you wish to continue without changing the algorithm then this code should work fine.
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n, sum;
int digits_array[5]={0}; //5 because it is a five digit number.
scanf("%d", &n);
int remainder_array[] = { n % 1000, n % 100, n % 10, n };//This is still a useless array this is kept so as to enter if.
// Complete the code to calculate the sum of the five digits on n.
if (10000 <= n && n <= 99999) {
if (remainder_array[0] != 0) {
digits_array[0] = (n) / 10000;//subtracting n with contents of remainder_array added to the complexity of the algorithm so took out the statement.
n =(n)%10000;
} if (remainder_array[1] != 0) {
digits_array[1] = (n) / 1000;
n =(n)%1000;
} if (remainder_array[2] != 0) {
digits_array[2] = (n) / 100;
n =(n)%100;
} if (remainder_array[3] != 0) {
digits_array[3] = (n)/10;
n=(n)%10;
}
digits_array[4]=n;//the last element of the number
}
sum = digits_array[0] + digits_array[1] + digits_array[2] + digits_array[3]+digits_array[4];
printf("%d",sum);
return 0;
}
Note: This program is not the best way and some changes are made refer to other answers for a more effective code and get the basics right before going to nested if condition.
Enjoy coding
I tried using the Miller-Rabin algorithm, but it can't detect very large numbers.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
long long mulmod(long long a, long long b, long long mod)
{
long long x = 0,y = a % mod;
while (b > 0)
{
if (b % 2 == 1)
{
x = (x + y) % mod;
}
y = (y * 2) % mod;
b /= 2;
}
return x % mod;
}
long long modulo(long long base, long long exponent, long long mod)
{
long long x = 1;
long long y = base;
while (exponent > 0)
{
if (exponent % 2 == 1)
{
x = (x * y) % mod;
}
y = (y * y) % mod;
exponent = exponent / 2;
}
return x % mod;
}
int Miller(unsigned long long int p, int iteration)
{
int i;
long long s;
if (p < 2)
{
return 0;
}
if (p != 2 && p % 2==0)
{
return 0;
}
s = p - 1;
while (s % 2 == 0)
{
s /= 2;
}
for (i = 0; i < iteration; i++)
{
long long a = rand() % (p - 1) + 1, temp = s;
long long mod = modulo(a, temp, p);
while (temp != p - 1 && mod != 1 && mod != p - 1)
{
mod = mulmod(mod, mod, p);
temp *= 2;
}
if (mod != p - 1 && temp % 2 == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int iteration = 5, cases;
unsigned long long int num;
scanf("%d", &cases);
for(int i = 0; i < cases; i++)
{
scanf("%llu", &num);
if(Miller(num, iteration))
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
return 0;
}
Output examples:
10 //cases
1
NO
2
YES
3
YES
4
NO
5
YES
1299827
YES
1951
YES
379
YES
3380
NO
12102
NO
I am trying to do my homework by creating a program that tells if a number is prime or not, print out YES if prime, NO if not. However, every time I submit the code to the online judge it just says "Wrong answer", when even my last attempt to do the assignment was without any efficient algorithm it says "Time limit exceeded".
Is there any way to determine if N is a prime number or not when N is [2 <= N <= 2^63-1]?
OP's code has many possibilities of overflowing 63-bit math. e.g. x * y in x = (x * y) % mod;
At a minimum, recommend to go to unsigned math. e.g.: long long --> unsigned long long or simply uintmax_t.
For a mulmod() that does not overflow: Modular exponentiation without range restriction.
I'll look more into this later. GTG.
I am trying to solve this tutorial practice question that doesn't have an answer that I can check my code against. The goal is to write a program to display numbers whose digits are 2 greater than the corresponding digits of the entered number. So if the number input is 5656 then the output number should be 7878. I have figured out how to separate each number and add them, but I can't seem to get them to print in a four-digit sequence.
#include <stdio.h>
int main ()
{
int n, one, two, three, four, final;
scanf("%d", &n);
one = (n / 1000);
n = (n % 1000) + 2;
two = (n / 100) + 2;
n = (n % 100) + 2;
three = (n / 10) + 2;
n = (n % 10) + 2;
four = (n / 1) + 2;
n = (n % 1) + 2;
final = (one * 1000) + (two * 100) + (three * 10) + four;
printf("%d", final);
return 0;
}
#include <stdio.h>
int main()
{
int n,a[4], final;
scanf("%d", &n);
for(int i=3;i>=0;i--)
{
a[i]=n%10+2;
n/=10;
}
final = (a[0] * 1000) + (a[1] * 100) + (a[2] * 10) + a[3];
printf("%d", final);
return 0;
}
Below function works with N number of digits.
Idea is to extract each digit from the input number and add its decimal position.
#include <stdio.h>
int power(int x, int y)
{
int res = 1;
for (;y>0;y--)
{
res *=x;
}
return res;
}
int main ()
{
int n;
scanf("%d", &n);
int sum = 0;
int i=0;
while(n>0)
{
sum += ((n%10) +2)*power(10,i);
i++;
n /=10;
}
printf("%d", sum);
return 0;
}
Another idea:
char str[10]; // enough to contain an int as string + 1
char *s = str+sizeof(str); // points to last char + 1
int n;
scanf("%d", &n);
*--s = 0; // terminate the string
while(n) {
*--s = (((n % 10)+2)%10) + '0'; // write a char from the end
n /= 10;
}
printf("%s\n", s);
int a = 5696;
// output is 7818
// ---------Java-----------
// --------solution--------
int first = a/1000+2;
int b = a%1000;
int second = b/100+2;
int c = b%100;
int d = c/10+2;
int third = d/10;
int e = c%10;
int fourth = e+2;
String result = Integer.toString(first)+Integer.toString(second)+Integer.toString(third)+Integer.toString(fourth);
System.out.println(result);
Lets say I have an integer called SIN and the scanf input receives 193456787.
so SIN = 193456787;
What I want to do is add up all the other numbers after the first digit.
So 9 + 4 + 6 + 8 = 27
Can somebody please explain to a beginner how to do this?
Print the number and then sum every other digit
int sum_every_other_digit_after_first(unsigned long long x) {
char buf[sizeof x * CHAR_BIT];
sprintf(buf, "%llu", x);
char *p = buf;
int sum = 0;
while (*p) {
p++; // Skip digit
if (*p) {
sum += *p++ - '0';
}
}
return sum;
}
or as inspired by #PageNotFound
int sum_every_other_digit_after_first(unsigned long long x) {
int esum = 0;
int osum = 0;
while (x > 0) {
esum += x%10;
x /= 10;
if (x == 0) {
return osum;
}
osum += x%10;
x /= 10;
}
return esum;
}
or for fun, a recursive solution
int sum_every_other_digit_after_first_r(unsigned long long x, int esum, int osum) {
if (x >= 100) {
int digit2 = x % 100;
esum += digit2 % 10;
osum += digit2 / 10
return sum_every_other_digit_after_first_r(x / 100, esum, osum);
}
if (x >= 10) {
return esum + x % 10;
}
return osum;
}
sum_every_other_digit_after_first_r(1234567,0,0) --> 12
My solution
#include <stdio.h>
int main()
{
int SIN = 193456787;
int a = 0, b = 0, cnt = 0;
while (SIN > 0) {
if (cnt % 2) b += SIN % 10;
else a += SIN % 10;
cnt++;
SIN /= 10;
}
printf("%d\n", cnt%2 ? b : a);
return 0;
}
Note: Please comment if this is not what you intended, as your question is a little ambigous.
#include <stdio.h>
int main() {
unsigned number;
scanf("%u\n", &number);
unsigned result = 0;
unsigned tmp = number;
unsigned numberOfDigits = 0;
do
numberOfDigits++;
while((tmp /= 10) != 0);
if(numberOfDigits % 2 != 0)
number /= 10;
while(number >= 10) {
result += number % 10;
number /= 100; // Skip two digits
}
printf("%u\n", result);
}
I would like to know how I can find the length of an integer in C.
For instance:
1 => 1
25 => 2
12512 => 5
0 => 1
and so on.
How can I do this in C?
C:
You could take the base-10 log of the absolute value of the number, round it down, and add one. This works for positive and negative numbers that aren't 0, and avoids having to use any string conversion functions.
The log10, abs, and floor functions are provided by math.h. For example:
int nDigits = floor(log10(abs(the_integer))) + 1;
You should wrap this in a clause ensuring that the_integer != 0, since log10(0) returns -HUGE_VAL according to man 3 log.
Additionally, you may want to add one to the final result if the input is negative, if you're interested in the length of the number including its negative sign.
Java:
int nDigits = Math.floor(Math.log10(Math.abs(the_integer))) + 1;
N.B. The floating-point nature of the calculations involved in this method may cause it to be slower than a more direct approach. See the comments for Kangkan's answer for some discussion of efficiency.
If you're interested in a fast and very simple solution, the following might be quickest (this depends on the probability distribution of the numbers in question):
int lenHelper(unsigned x) {
if (x >= 1000000000) return 10;
if (x >= 100000000) return 9;
if (x >= 10000000) return 8;
if (x >= 1000000) return 7;
if (x >= 100000) return 6;
if (x >= 10000) return 5;
if (x >= 1000) return 4;
if (x >= 100) return 3;
if (x >= 10) return 2;
return 1;
}
int printLen(int x) {
return x < 0 ? lenHelper(-x) + 1 : lenHelper(x);
}
While it might not win prizes for the most ingenious solution, it's trivial to understand and also trivial to execute - so it's fast.
On a Q6600 using MSC I benchmarked this with the following loop:
int res = 0;
for(int i = -2000000000; i < 2000000000; i += 200) res += printLen(i);
This solution takes 0.062s, the second-fastest solution by Pete Kirkham using a smart-logarithm approach takes 0.115s - almost twice as long. However, for numbers around 10000 and below, the smart-log is faster.
At the expense of some clarity, you can more reliably beat smart-log (at least, on a Q6600):
int lenHelper(unsigned x) {
// this is either a fun exercise in optimization
// or it's extremely premature optimization.
if(x >= 100000) {
if(x >= 10000000) {
if(x >= 1000000000) return 10;
if(x >= 100000000) return 9;
return 8;
}
if(x >= 1000000) return 7;
return 6;
} else {
if(x >= 1000) {
if(x >= 10000) return 5;
return 4;
} else {
if(x >= 100) return 3;
if(x >= 10) return 2;
return 1;
}
}
}
This solution is still 0.062s on large numbers, and degrades to around 0.09s for smaller numbers - faster in both cases than the smart-log approach. (gcc makes faster code; 0.052 for this solution and 0.09s for the smart-log approach).
int get_int_len (int value){
int l=1;
while(value>9){ l++; value/=10; }
return l;
}
and second one will work for negative numbers too:
int get_int_len_with_negative_too (int value){
int l=!value;
while(value){ l++; value/=10; }
return l;
}
You can write a function like this:
unsigned numDigits(const unsigned n) {
if (n < 10) return 1;
return 1 + numDigits(n / 10);
}
length of n:
length = ( i==0 ) ? 1 : (int)log10(n)+1;
The number of digits of an integer x is equal to 1 + log10(x). So you can do this:
#include <math.h>
#include <stdio.h>
int main()
{
int x;
scanf("%d", &x);
printf("x has %d digits\n", 1 + (int)log10(x));
}
Or you can run a loop to count the digits yourself: do integer division by 10 until the number is 0:
int numDigits = 0;
do
{
++numDigits;
x = x / 10;
} while ( x );
You have to be a bit careful to return 1 if the integer is 0 in the first solution and you might also want to treat negative integers (work with -x if x < 0).
A correct snprintf implementation:
int count = snprintf(NULL, 0, "%i", x);
The most efficient way could possibly be to use a fast logarithm based approach, similar to those used to determine the highest bit set in an integer.
size_t printed_length ( int32_t x )
{
size_t count = x < 0 ? 2 : 1;
if ( x < 0 ) x = -x;
if ( x >= 100000000 ) {
count += 8;
x /= 100000000;
}
if ( x >= 10000 ) {
count += 4;
x /= 10000;
}
if ( x >= 100 ) {
count += 2;
x /= 100;
}
if ( x >= 10 )
++count;
return count;
}
This (possibly premature) optimisation takes 0.65s for 20 million calls on my netbook; iterative division like zed_0xff has takes 1.6s, recursive division like Kangkan takes 1.8s, and using floating point functions (Jordan Lewis' code) takes a whopping 6.6s. Using snprintf takes 11.5s, but will give you the size that snprintf requires for any format, not just integers. Jordan reports that the ordering of the timings are not maintained on his processor, which does floating point faster than mine.
The easiest is probably to ask snprintf for the printed length:
#include <stdio.h>
size_t printed_length ( int x )
{
return snprintf ( NULL, 0, "%d", x );
}
int main ()
{
int x[] = { 1, 25, 12512, 0, -15 };
for ( int i = 0; i < sizeof ( x ) / sizeof ( x[0] ); ++i )
printf ( "%d -> %d\n", x[i], printed_length ( x[i] ) );
return 0;
}
Yes, using sprintf.
int num;
scanf("%d",&num);
char testing[100];
sprintf(testing,"%d",num);
int length = strlen(testing);
Alternatively, you can do this mathematically using the log10 function.
int num;
scanf("%d",&num);
int length;
if (num == 0) {
length = 1;
} else {
length = log10(fabs(num)) + 1;
if (num < 0) length++;
}
int digits=1;
while (x>=10){
x/=10;
digits++;
}
return digits;
sprintf(s, "%d", n);
length_of_int = strlen(s);
You may use this -
(data_type)log10(variable_name)+1
ex:
len = (int)log10(number)+1;
In this problem , i've used some arithmetic solution . Thanks :)
int main(void)
{
int n, x = 10, i = 1;
scanf("%d", &n);
while(n / x > 0)
{
x*=10;
i++;
}
printf("the number contains %d digits\n", i);
return 0;
}
Quite simple
int main() {
int num = 123;
char buf[50];
// convert 123 to string [buf]
itoa(num, buf, 10);
// print our string
printf("%s\n", strlen (buf));
return 0;
}
keep dividing by ten until you get zero, then just output the number of divisions.
int intLen(int x)
{
if(!x) return 1;
int i;
for(i=0; x!=0; ++i)
{
x /= 10;
}
return i;
}
This goes for both negative and positive intigers
int get_len(int n)
{
if(n == 0)
return 1;
if(n < 0)
{
n = n * (-1); // if negative
}
return log10(n) + 1;
}
Same logic goes for loop
int get_len(int n)
{
if(n == 0)
return 1;
int len = 0;
if(n < 0)
n = n * (-1);
while(n > 1)
{
n /= 10;
len++;
}
return len;
}
Why don't you cast your integer to String and get length like this :
int data = 123;
int data_len = String(data).length();
For simple programs...
int num = 456, length=0 // or read value from the user to num
while(num>0){
num=num/10;
length++;
}
Use another variable to retain the initial num value.
In my opinion the shortest and easiest solution would be:
int length , n;
printf("Enter a number: ");
scanf("%d", &n);
length = 0;
while (n > 0) {
n = n / 10;
length++;
}
printf("Length of the number: %d", length);
My way:
Divide as long as number is no more divisible by 10:
u8 NumberOfDigits(u32 number)
{
u8 i = 1;
while (number /= 10) i++;
return i;
}
I don't know how fast is it in compared with other propositions..
int intlen(int integer){
int a;
for(a = 1; integer /= 10; a++);
return a;
}
A more verbose way would be to use this function.
int length(int n)
{
bool stop;
int nDigits = 0;
int dividend = 1;
do
{
stop = false;
if (n > dividend)
{
nDigits = nDigits + 1;
dividend = dividend * 10;
}
else {
stop = true;
}
}
while (stop == false);
return nDigits;
}
int returnIntLength(int value){
int counter = 0;
if(value < 0)
{
counter++;
value = -value;
}
else if(value == 0)
return 1;
while(value > 0){
value /= 10;
counter++;
}
return counter;
}
I think this method is well suited for this task:
value and answers:
-50 -> 3 //it will count - as one character as well if you dont want to count
minus then remove counter++ from 5th line.
566666 -> 6
0 -> 1
505 -> 3
Solution
Use the limit where the integer length changes, in the case of the decimal it is a power of 10, and thus use a counter for each verification that the specified integer has not exceeded the limit.
With the math.h dependency:
#include <math.h>
int count_digits_of_integer(unsigned int integer) {
int count = 1;
while(1) {
int limit = pow(10, count);
if(integer < limit) break;
count++;
}
return count;
}
Without dependency:
int int_pow(int base, int exponent) {
int potency = base;
for(int i = 1; i < exponent; i++) potency *= base;
return potency;
}
int count_digits_of_integer(unsigned int integer) {
int count = 1;
while(1) {
int limit = int_pow(10, count);
if(integer < limit) break;
count++;
}
return count;
}
Implementation
#include <stdio.h>
// Copy and paste the solution code here
int main() {
printf("%i -> (%i digits)\n", 0, count_digits_of_integer(0));
printf("%i -> (%i digits)\n", 12, count_digits_of_integer(12));
printf("%i -> (%i digits)\n", 34569, count_digits_of_integer(34569));
printf("%i -> (%i digits)\n", 1234, count_digits_of_integer(1234));
printf("%i -> (%i digits)\n", 3980000, count_digits_of_integer(3980000));
printf("%i -> (%i digits)\n", 100, count_digits_of_integer(100));
printf("%i -> (%i digits)\n", 9, count_digits_of_integer(9));
printf("%i -> (%i digits)\n", 385784, count_digits_of_integer(385784));
return 0;
}
Output:
0 -> (1 digits)
12 -> (2 digits)
34569 -> (5 digits)
1234 -> (4 digits)
3980000 -> (7 digits)
100 -> (3 digits)
9 -> (1 digits)
385784 -> (6 digits)
Hmm, maybe like this...?
#define _LEN(x) (sizeof(#x)/sizeof(char)-1)
You can also use this function to find the length of an integer:
int countlength(int number)
{
static int count = 0;
if (number > 0)
{
count++;
number /= 10;
countlength(number);
}
return count;
}
I think I got the most efficient way to find the length of an integer
its a very simple and elegant way
here it is:
int PEMath::LengthOfNum(int Num)
{
int count = 1; //count starts at one because its the minumum amount of digits posible
if (Num < 0)
{
Num *= (-1);
}
for(int i = 10; i <= Num; i*=10)
{
count++;
}
return count;
// this loop will loop until the number "i" is bigger then "Num"
// if "i" is less then "Num" multiply "i" by 10 and increase count
// when the loop ends the number of count is the length of "Num".
}
int main(void){
unsigned int n, size=0;
printf("get the int:");
scanf("%u",&n);
/*the magic*/
for(int i = 1; n >= i; i*=10){
size++;
}
printf("the value is: %u \n", n);
printf("the size is: %u \n", size);
return 0;
}
#include <stdio.h>
int main(void){
int c = 12388884;
printf("length of integer is: %d",printf("%d",c));
return 0;
}