finding the sum of a given Int but ignoring duplicate numbers - c

I can't use arrays or lists and I have to use C.
Duplicates mean if you have 975444579 it will show 25 or if you have 32111 it will show 6 and not 8.
Here is my code:
#include <stdio.h>
int main() {
int num = 0, sum = 0, i = 0, oNum = 0, nNum = 0, tNum = 0, e = 0;
printf("enter a number: ");
scanf("%d", &num);
oNum = num;
while (num != 0) {
e = 0;
i = 0;
nNum = oNum;
tNum = num % 10;
do {
if (nNum % 10 == tNum) {
i += 1;
}
nNum /= 10;
} while (nNum != 0);
sum += tNum;
i -= 1;
while (e < i) {
sum -= tNum;
e += 1;
}
num /= 10;
}
printf("%d", sum);
return 0;
}

Not being able to use an array is a silly requirement. It lends itself well to the problem:
Initial:
int seen[10] = { 0 };
Checking if a digit was encountered:
seen[d]
Marking a digit as encountered:
++seen[d];
These could even be combined.
if (!(seen[d]++))
sum += d;
But, we could use 10 bits of a number in a similar manner.
Initial:
uint16_t seen = 0;
Checking if a bit is set is done as follows:
seen & (1 << d)
Setting a bit is done as follows:
seen |= 1 << d;

finding the sum of a given Int but ignoring duplicate numbers digits?
Form a mask of allowed digits
Iterate once extracting one digit at a time (OP has that part)
If digit not used before, clear that a bit (per digit) and add digit to the sum.
Let us use an unsigned integer to avoid complications with negative values - we'll disallow them.
int digit_sum_no_repeat(unsigned i) {
int sum = 0;
unsigned allowed_digits_mask = 0x3FF; // All 10 digits allowed.
while (i) {
unsigned digit = i % 10; // Extract least significant digit
unsigned digit_mask = 1u << digit;
if (allowed_digits_mask & digit_mask) {
allowed_digits_mask ^= digit_mask; // clear the bit
sum += digit;
}
i /= 10;
}
return sum;
}

Here's a working example that uses the bits of a single unsigned int to find each digit in a number, and which then adds those found digits:
#include <stdio.h>
int main()
{
int num = 0, sum = 0, i;
unsigned int digits = 0u; // MUST be at least 10 bits in size (which is guaranteed)
printf("enter a number: ");
scanf("%d", &num);
while (num != 0) { // first loop - set bits for each digit present:
int dig = num % 10; // This gets us the value of the lowest digit...
digits |= (1u << dig); // Set the bit to indicate this digit.
num /= 10; // .. now remove the lowest digit and 'shift' the others.
}
for (i = 1; i < 10; ++i) { // second loop - sum all digits whose corresponding bit is set:
if (digits & (1u << i)) sum += i;
}
printf("%d", sum);
return 0;
}

unsigned int n = 1231;
unsigned int nsum = 0;
unsigned int bdigits = 0;
while( n ) {
bdigits |= 1 << (n%10);
n /= 10;
}
for( unsigned int x = 0; x < 10; x++ ) {
if( bdigits&(1<<x) ) nsum += x;
}
printf("Sum: %d\n", nsum);

I use switch loop two times ,but the code is so long
#include <stdio.h>
int main() {
int num=0,zero=0,one=0,two=0,three=0,four=0,five=0,six=0,seven=0,eight=0,nine=0,ten=0,s=0;
printf("enter a number: ");
scanf("%d", &num);
while(num != 0)
{
switch(num%10)
{
case 0:
{
zero++;
switch(zero)
{
case 1:
{
s=s+0;
}break;
}
}break;
case 1:
{
one++;
switch(one)
{
case 1:
{
s=s+1;
}break;
}
}break;
case 2:
{
two++;
switch(two)
{
case 1:
{
s=s+2;
}break;
}
}break;
case 3:
{
three++;
switch(three)
{
case 1:
{
s=s+3;
}break;
}
}break;
case 4:
{
four++;
switch(four)
{
case 1:
{
s=s+4;
}break;
}
}break;
case 5:
{
five++;
switch(five)
{
case 1:
{
s=s+5;
}break;
}
}break;
case 6:
{
six++;
switch(six)
{
case 1:
{
s=s+6;
}break;
}
}break;
case 7:
{
seven++;
switch(seven)
{
case 1:
{
s=s+7;
}break;
}
}break;
case 8:
{
eight++;
switch(eight)
{
case 1:
{
s=s+8;
}break;
}
}break;
case 9:
{
nine++;
switch(nine)
{
case 1:
{
s=s+9;
}break;
}
}break;
}
num /= 10;
}
printf("\nThe sum of the digits exepting repeated value : %d\n",s);
return 0;
}

You can do a trick using files and numbers, without needing to use array as follows:
int main()
{
int num;
char c;
FILE *fp = fopen("temp", "w");
if(!fp)
{
exit(1);
}
printf("enter a number: ");
scanf("%d", &num);
fprintf(fp, "%d", num);
fclose(fp);
int mask = 0;
fp = fopen("temp", "r");
while(fscanf(fp, "%1d", &num) != EOF) // reading 1 digit at a time
{
mask |= (1 << num); // here you will set the bit referent to the digit
}
fclose(fp);
int sum = 0;
for(int i = 1; i < 10; i++)
{
if(mask & (1 << i)) // here you check if the bit referent to number i was set
{
sum += i;
}
}
printf("sum is %d\n", sum);
}
Another way without the file is:
int main()
{
int num;
printf("enter a number: ");
scanf("%d", &num);
int mask = 0;
while(num)
{
mask |= (1 << (num%10));
num = num/10;
}
int sum = 0;
for(int i = 1; i < 10; i++)
if(mask & (1 << i))
sum += i;
printf("sum is %d\n", sum);
}

It's very hard to follow your program to debug it. You should choose more meaningful variable names or fill the code with all the required comments. Here's a program with better names.
#include <stdio.h>
int main() {
int num, check, copy, digit, notAdupe, sum = 0;
printf("enter a number: ");
scanf("%d", &num);
for(check = num; check; check /= 10 ) {
digit = check % 10;
notAdupe = 1;
for(copy = num; copy > check; copy /= 10) {
if( digit == copy % 10 ) {
notAdupe = 0;
break;
}
}
if( notAdupe ) sum += digit;
}
printf("\n%d", sum);
return 0;
}

in this block:
do {
if (nNum % 10 == tNum)
{
i += 1;
}
nNum /= 10;
} while (nNum != 0);
i -= 1;
you count how many times tNum appear in the digits that in his left side, so in the number 32111 for example you subtracting the most left 1 twice.
you need a way to find out if this the first time for seeing the digit in tNum.you can do it with bitwise of int variable with somethis like this
int flag = 0;
int is_first = 0;
...
tNum = num % 10;
is_first = flag ^ (tNum << 1) > flag;
flag |= (tNum << 1);
the flag will save in his bits which number you already saw
for example:
num = 121:
// you start with
flag = 0
...
tNum = 1, flag = 0 so
is_first = 0 ^ (1 << 1) > 0 = 1 > 0('true')
flag = 0 | 1 = 1
...
tNum = 2, flag = 1 so
is_first = 1 ^ (2 << 1) > 1 = 3 > 1('true')
flag = 2 | 1 = 3
...
tNum = 1, flag = 3 so
is_first = 3 ^ (1 << 1) > 3 = 2 > 3('false')
flag = 3 | 1 = 1

Here is a much simpler function to compute the sum of unique decimal digits in an integer:
int sum_unique_digits(unsigned n) {
int sum = 0, bits = 0;
do {
bits |= 1 << (n % 10);
} while (n /= 10);
do {
sum += (bits & 1) * n++;
} while (bits >>= 1);
return sum;
}

Related

sum of all the digit of a number using while-loop in C

I'm trying to solve a problem (as the title already state). I've actually learned that I can do it with modulo operator (%). But the first code that I wrote is using the while-loop, so I'm trying to finish the code.
This is the code
int main()
{
char arr[1000000];
int i = 0;
int sum = 0;
printf("type the number = ");
scanf("%s", arr);
while(arr[i] != '\0'){
sum = arr[i] + sum;
i++;
}
printf("the total number is = %d", sum);
so the problem is it's actually printing out some huge amount of number.. I guess it's because of the array is in char, can someone help me how do I changed the value into int ?
You need to substract from the digit code the code of '0'.
Here you have the both versions (I have added some logic to accept the numbers with + & - at there beginning):
int sumdigitsStr(const char *num)
{
int sum = 0;
int first = 1;
while(*num)
{
if(isdigit(*num)) {sum += *num - '0'; first = 0;}
else
if(first && (*num == '-' || *num == '+'))
{
first = 0;
num++;
continue;
}
else
{
sum = -1; break;
} //error string contains non digits
num++;
}
return sum;
}
int sumdigits(long long num)
{
int sum = 0;
do
{
sum += abs((int)(num % 10));
}while((num = num / 10));
return sum;
}
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n);
int d, sum = 0;
while (n != 0)
{
d = n % 10;
sum = sum + d;
n = n / 10;
}
printf("sum of digits is : %d", sum);
return 0;
}

How to express integer as a product of its prime factors?

//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
printf("%d ", i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
}
}
I know that this is the way of finding the prime factors of a number using for loop. But I don't know how to express the output integer as a product of its prime factors.
For example, INPUT IS: 10 ||
OUTPUT IS: 2 x 5 = 10. How do we do this? TIA.
You should:
Save the original value.
Print the operator x between each prime factors.
Print the original value at the end.
#include <stdio.h>
int main(void) {
int num;
int i;
int start_num;
int is_first = 1;
if(scanf("%d", &num) != 1) return 1;
start_num = num; //Save the original value.
//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
if(!is_first) printf("x "); //Print the operator before second and later operands.
printf("%d ", i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
is_first = 0; //Mark that there is already one or more operand.
}
}
printf("= %d\n", start_num); //Print the original value.
return 0;
}
You can output the factors with the appropriate punctuation:
// Output the prime factors of a number
void factorize(int num) {
int n = num; // save the initial value of num
const char *sep = ""; // initial separator is an empty string
for (int i = 2; i <= num / i; i++) { // stop when num is reduced to a prime
while (num % i == 0) { // while the input is divisible to "i"
num = num / i; // divide the num by "i" (remove the factor)
printf("%s%d", sep, i); // print the separator and the factor.
sep = " x "; // change the separator for any further factors
}
}
if (num > 1 || n <= 1) {
printf("%s%d", sep, num); // print the last or single factor.
}
printf(" = %d\n", n); // print the rest of the equation
}
I've revised the code to give something that's a bit more robust than what I posted previously, as well as being slightly more efficient. Again I assume you want (unsigned) 32-bit input via stdin in the range: [1, 2^32 - 1]
As far as the algorithm is concerned, it should be apparent that searching for factors need only test candidates up to floor(sqrt(num)). There are also factors with multiplicity, e.g., (24) => {2, 2, 2, 3}.
Furthermore, after factoring out (2), only odd factors need to be tested.
For a 32-bit (unsigned) type, there will be fewer than (32) prime factors. This gives a simple upper-bound for a fixed-size array for storing the successive prime factors. The prime factors in the array are in ascending order, by virtue of the algorithm used.
/******************************************************************************/
#include <stdio.h>
int main (void)
{
/* print a value in [1, 2^32 - 1] as a product of primes: */
unsigned long int n, u, prime[32];
int np = 0;
if (scanf("%lu", & n) != 1 ||
((n == 0) || ((n & 0xffffffffUL) != n)))
{
fprintf(stderr, "factor < u32 = 1 .. 2^32 - 1 >\n");
return (1);
}
if (n == 1) /* trivial case: */
{
fprintf(stdout, "1 = 1\n");
return (0);
}
u = n; /* (u) = working value for (n) */
for (; (u & 0x1) == 0; u >>= 1) /* while (u) even: */
prime[np++] = (2);
while (u > 1)
{
unsigned long q, d = 3, c = 0; /* (c)omposite */
if (np != 0) /* start at previous odd (prime) factor: */
d = (prime[np - 1] == 2) ? (3) : prime[np - 1];
for (; (c == 0) && (q = u / d) >= d; )
{
if ((c = (q * d == u)) == 0) /* not a factor: */
d += 2;
}
prime[np++] = (d = (c == 0) ? u : d);
u /= d; /* if (u) is prime, ((u /= d) == 1) (done) */
}
for (int i = 0; i < np; i++)
{
const char *fmt = (i < np - 1) ? ("%lu x ") : ("%lu = ");
fprintf(stdout, fmt, prime[i]);
}
fprintf(stdout, "%lu\n", n);
return (0);
}
/******************************************************************************/

Sum of digits not including the same digit twice

(Purpose of the code is write in the title) my code work only if i put the same number once and in the end like - 123455 but if i write 12345566 is dosent work or 11234 it dosent wort to someone know why? i have been trying for a few days and i faild agine and agine.
while(num)
{
dig = num % 10 // dig is the digit in the number
num /= 10 // num is the number the user enter
while(num2) // num2 = num
{
num2 /= 10
dig2 = num2 % 10 // dig2 is is the one digit next to dig
num2 /= 10
if(dig2 == dig) // here I check if I got the same digit twice to
// not include him
{
dig2 = 0
dig = 0
}
}
sum = sum + dig + hold
}
printf("%d", sum)
Well your code's almost correct but there's are somethings wrong ,
When you declared num2 to be equal to num1 it was out of the loop so as soon as one full loop execution is done , num2 still remains to be less than zero or to be zero if it was a unsigned int, so according to the condition the second loop wont execute after its first run.
So mind adding ,
num2 = num1
inside your first loop .
Also your updating num2 twice which i think you wont need to do after the first change .
Full code which i tried
#include<stdio.h>
int main(void)
{
int num;
int num2;
int sum = 0;
int dig, dig2;
scanf_s("%d", &num);
while (num>0)
{
dig = num % 10; //dig is the digit in the number
num /= 10;
num2 = num;// num is the number the user enter
while (num2>0) // num2 = num
{
dig2 = num2 % 10; // dig2 is is the one digit next to dig
if(dig2 == dig) // here i check if i got the same digit twice to //not include him
{
dig = 0;
}
num2 /= 10;
}
sum = sum + dig ;
}
printf("%d", sum);
return 0;
}
O(n)
#include <stdio.h>
int main () {
unsigned int input = 0;
printf("Enter data : ");
scanf("%u", &input);
int sum = 0;
int dig = 0;
int check[10] = {0};
printf("Data input: %u\n", input);
while(input) {
dig = 0;
dig = input%10;
input = input/10;
if (check[dig] == 0) {
check[dig]++;
sum += dig;
}
}
printf("Sum of digits : %d\n", sum);
return 0;
}
My program uses a character array (string) for storing an integer. We convert its every character into an integer and I remove all integers repeated and I calculate the sume of integers without repetition
My code :
#include <stdio.h>
#include <stdlib.h>
int remove_occurences(int size,int arr[size])
{int s=0;
for (int i = 0; i < size; i++)
{
for(int p=i+1;p<size;p++)
{
if (arr[i]==arr[p])
{
for (int j = i+1; j < size ;j++)
{
arr[j-1] = arr[j];
}
size--;
p--;
}
}
}
for(int i=0;i<size;i++)
{
s=s+arr[i];
}
return s;
}
int main()
{
int i=0, sum=0,p=0;
char n[1000];
printf("Input an integer\n");
scanf("%s", n);
int T[strlen(n)];
while (n[i] != '\0')
{
T[p]=n[i] - '0'; // Converting character to integer and make it into the array
p++;i++;
}
printf("\nThe sum of digits of this number :%d\n",remove_occurences(strlen(n),T));
return 0;
}
Example :
Input : 1111111111 Output : 1
Input : 12345566 Output : 21
Or ,you can use this solution :
#include <stdio.h>
#include <stdbool.h>
bool Exist(int *,int,int);
int main ()
{
unsigned int n = 0;
int m=0,s=0;
printf("Add a number please :");
scanf("%u", &n);
int T[(int)floor(log10(abs(n)))+1];
// to calculate the number of digits use : (int)floor(log10(abs(n)))+1
printf("\nThe length of this number is : %d\n",(int)floor(log10(abs(n)))+1);
int p=0;
while(n!=0)
{
m=n%10;
if(Exist(T,p,m)==true)
{
T[p]=m;
p++;
}
n=n/10;
}
for(int i=0;i<p;i++)
{
s=s+T[i];
}
printf("\nSum of digits : %d\n", s);
return 0;
}
bool Exist(int *T,int k,int c)
{
for(int i=0;i<k;i++)
{
if(T[i]==c)
{
return false;
}
}
return true;
}

how do I add up the sum of the digits of a number except for digits that repeat themselves in c?

I have an assignment and I need to add up the digits of it and ignore the once that repeat themselves
for example 234111 -> 2 + 3 + 4 + 1 -> 10
I tried doing this:
#include
int main(void)
{
int i = 0;
int num = 0;
int sum = 0;
printf("Please enter a number\n");
scanf("%d", &num);
while(num > 0){
sum += num%10;
num /= 10;
}
printf("%d", sum);
return 0;
}
what I did just adds up the digits, it doesn't ignore that ones that get repeated
What do i need to add to the code?
You can keep an array of 'flags' for which digits have been used already:
#include <stdio.h>
int main(void)
{
// int i = 0; // You don't actually use this in the code!
int num = 0;
int sum = 0;
int used[10] = { 0, }; // Set all "used" flags to zero
printf("Please enter a number\n");
scanf("%d", &num);
while (num > 0)
{
int digit = num % 10; // Get the digit
if (!used[digit]) sum += digit; // Only add if not used already
used[digit] = 1; // Now we have used it!
num /= 10;
}
printf("%d", sum);
return 0;
}
Feel free to ask for further clarification and/or explanation.
Just read each character and record if you've already seen it:
#include <stdio.h>
#include <ctype.h>
int
main(void)
{
int seen[10] = {0};
int sum = 0;
int c;
while( ( c = getchar()) != EOF ) {
int v = c - '0';
if( isspace(c)) {
continue;
}
if( v < 0 || v > 9 ) {
fprintf(stderr, "Invalid input\n");
return 1;
}
if( ! seen[v]++ )
sum += v;
}
printf("%d\n", sum);
return 0;
}

Need 10 outputs per line

I am having trouble refining some code. My code takes a number "n" and calculates that many prime numbers. I need to display 10 primes per line of output data. Any tips would be appreciated.
#include <stdio.h>
int main()
{
int n, i = 3, count, c;
printf("How many primes would you like?");
scanf("%d",&n);
if ( n >= 1 )
{
printf("2");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf(" %d",i);
count++;
}
i++;
}
return 0;
}
Just try
printf(" %5d", i);
/* ^ to help align the numbers
and
if ((count + 1) % 10 == 0)
fputc(stdout, '\n');
fix for the first time when you already print 2.
bool is_prime(int anyNum) //takes an integer array returns, is_prime
{
bool is_prime = true;
for (int c = 2; c <= anyNum - 1; c++)
{
if (anyNum % c == 0)
{
//printf("%d is not prime\r\n" , anyNum);
is_prime = false;
}
}
return is_prime;
}
int main()
{
int num_primes;
printf("How many primes would you like: ");
std::cin >> num_primes;
printf("\r\nScanned Primes Are---\r\n");
int foundPrimes = 0;
int x = 0;
for (; x <= num_primes; x++)
{
bool gotLuckyFindingPrime = is_prime( x );
if (gotLuckyFindingPrime)
{
if (foundPrimes % 10 == 0)
{
printf("\r\n");
}
printf(" %d", x);
foundPrimes = (foundPrimes + 1) % 10;
}
}
}
Does handle ten digit showing on cmd too, you can experiment with formatting

Resources