I need to add the digits on the even and odd places in an integer. Say, Let number = 1234567. Sum of even place digits = 2+4+6 = 12 Sum of odd place digits = 1+3+5+7 = 16
The code I currently have is:
int returnsum(int num) {
while (num) {
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
while (sum) {
a = sum % 10;
arr[i] = a:
sum = sum / 10;
i++;
}
for (i = 0; a[i]; i += 2) {
summ = summ + a[i];
}
return summ;
}
void main() {
int n, m, oddSum = 0, evenSum = 0;
printf("Please insert the number for the program:");
scanf("%d", & n);
while (n != 0) {
oddSum += n % 10;
n /= 10;
evenSum += n % 10;
n /= 10;
}
printf("Sum of digits in even places:%d\n", evenSum);
printf("Sum of digits in odd places:%d\n", oddSum);
}
Here is a solution for your problem:
void main()
{
int n,m,oddSum=0,evenSum=0;
printf("Please insert the number for the program:");
scanf("%d",&n);
int flag=0;
int counter=1;
while (n!=0) {
if(counter%2==0)
{
evenSum += n % 10;
n /= 10;
}
else
{
oddSum += n % 10;
n /= 10;
}
counter++;
}
if(counter%2==0)
{
int temp=oddSum;
oddSum=evenSum;
evenSum=temp;
}
printf("Sum of digits in even places:%d\n",evenSum);
printf("Sum of digits in odd places:%d\n",oddSum);
}
Okay, let's first assume the number has an even number of digits, so that the second-last and last are at odd and even positions respectively.
Then, the last digit can be retrieved with number % 10 and the second last with (number / 10) % 10.
So, knowing that, you can simply loop over the number, adding those values and dividing by a hundred until you get a number less than ten.
If that number is zero, then your assumption about the original having an even number of digits was correct and you can exit.
If it's a non-zero (1..9), then your assumption was wrong, you should swap the even and odd sums to date then add the final digit to the odd sum.
The pseudo-code goes something like this:
def getEvenOdd (num):
even = 0
odd = 0
while num > 9:
even = even + (num % 10)
odd = odd + ((num / 10) % 10)
num = num / 100
if num > 0:
temp = even
even = odd
odd = temp
odd = odd + num
return (even,odd)
print getEvenOdd(1234567)
And the output of that would be something like (12,16).
And it's no accident that pseudo-code looks like beginner's Python, since that language is the perfect pseudo-code language, provided you don't mess about with the more complex corners of it.
Check the below code:
#include <stdio.h>
int main(void){
char p[20];
int i=0,even=0,odd=0,n;
scanf("%d",&n);
sprintf(p,"%d",n);
while(p[i] != '\0')
{
if(i%2 == 0)
odd+= (p[i] - '0');
else
even+= (p[i] - '0');
i++;
}
printf("%d\n",even);
printf("%d\n",odd);
return 0;
}
To sum every other digit, simply divide by 100 in each iteration:
int sumodd(int num) {
int sum = 0, rem;
while(num) {
rem=num%10;
sum=sum+rem;
num=num/100);
}
return sum;
}
Since we already have a function that can sum every other digit, we can re-use it:
int sumeven(int num) {
return sumodd(num/10);
}
My five cents.:)
#include <stdio.h>
typedef struct pair
{
unsigned int odd;
unsigned int even;
} pair_t;
pair_t GetSums( unsigned int x )
{
const unsigned int Base = 10;
pair_t sums = { 0u, 0u };
size_t n = 0;
do
{
if ( ++n & 1 ) sums.odd += x % Base;
else sums.even += x % Base;
} while ( x /= Base );
if ( ( n & 1 ) == 0 )
{
unsigned int tmp = sums.odd;
sums.odd = sums.even;
sums.even = tmp;
}
return sums;
}
int main(void)
{
while ( 1 )
{
unsigned int x;
pair_t sums;
printf( "\nEnter a non-negative number (0 - exit): " );
if ( scanf( "%u", &x ) != 1 || x == 0 ) break;
sums = GetSums( x );
printf( "\nSum of digits in odd positions is %u\n", sums.odd );
printf( "Sum of digits in even positions is %u\n", sums.even );
}
return 0;
}
The output might look like
Enter a non-negative number (0 - exit): 1234567
Sum of digits in odd positions is 16
Sum of digits in even positions is 12
Enter a non-negative number (0 - exit): 123456
Sum of digits in odd positions is 9
Sum of digits in even positions is 12
Enter a non-negative number (0 - exit): 0
Related
I wrote this program to find prime numbers between 1 and 50000, and I still need to find how many prime numbers there is (I tried a lot of tricks but I did not succeed)
#include <stdio.h>
//int getValueFromUser();
void PrintListOfPrime(int value);
int main() {
int value = 23;
PrintListOfPrime(value);
return 0;
}
void PrintListOfPrime(int value) {
int ValueIsPrime; //ValueIsPrime is used as flag variable
printf("The list of primes: ");
for (int i = 2; i <= value; i++) {
ValueIsPrime = 1;
/* Check if the current number i is prime or not */
for (int j = 2; j <= i / 2; j++) {
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if (i % j == 0) {
ValueIsPrime = 0;
break;
}
}
/* If the number is prime then print */
if (ValueIsPrime == 1)
printf("%d, ", i);
}
printf("\n");
}
I tried a lot of tricks but I did not succeed
If OP's code takes too long to ran, iterate to the square root of i, not up to i/2.
j <= i / 2 is very slow. Use j <= i / j instead.
Form a count and increment with every prime. #gspr
if (ValueIsPrime == 1) {
printf("%d, ", i);
prime_count++;
}
Bigger change yet even faster to "find prime numbers between 1 and 50000", research Sieve of Eratosthenes
Hello fast answer is to create a variable in main, int totaleOfPrimes = 0; for example.
then send it by reference to the fucntion :
Function declaration : void PrintListOfPrime(int value,int* counter);
Function call : void PrintListOfPrime(value,&totaleOfPrimes);
then Increment counter befor printing :
if (ValueIsPrime == 1){
(*counter)++;
printf("%d, ", i);
}
There is no need to iterate the loops for all numbers between 2 and value. You should consider only 2 and odd numbers.
The function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
static inline size_t PrintListOfPrime( unsigned int n )
{
size_t count = 0;
printf( "The list of primes:\n" );
for ( unsigned int i = 2; i <= n; i = i != 2 ? i + 2 : i + 1 )
{
int isPrime = 1;
/* Check if the current number i is prime or not */
for ( unsigned int j = 3; isPrime && j <= i / j; j += 2 )
{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
isPrime = i % j != 0;
}
/* If the number is prime then print */
if ( isPrime )
{
if ( ++count % 14 == 0 ) putchar( '\n' );
printf( "%u ", i );
}
}
return count;
}
int main(void)
{
unsigned int n = 50000;
size_t count = PrintListOfPrime( n );
printf( "\n\nThere are %zu prime numbers up to %u\n", count, n );
return 0;
}
Run this code in C. It will return the value of a pi(x) function. It is basically the Prime counting function:
#include <stdio.h>
#define LEAST_PRIME 2
#include <math.h>
int main() //works for first 10000 primes.
{
int lower_limit = 2, no_of_sets;
// printf("NUMBER OF SETS: ");
// scanf("%d", &no_of_sets);
int remainder, divisor = 2, remainder_dump, upper_limit; //upper limit to be specified
//by user.
int i = 1;
// printf("SPECIFY LOWER LIMIT: ");
// scanf("%d", &lower_limit);
int number_to_be_checked = lower_limit;
printf("SPECIFY UPPER LIMIT: ");
scanf("%d", &upper_limit);
printf("2\t\t\t\t", number_to_be_checked);
//PRINTS 2.*/
do
{
remainder_dump = 1;
divisor = 2;
do
{
remainder = number_to_be_checked % divisor;
if (remainder == 0)
{
remainder_dump = remainder_dump * remainder; // dumping 0 for rejection.
break;
}
++divisor;
} while (divisor <= number_to_be_checked / divisor); // upto here we know number
is prime or not.
if (remainder_dump != 0)
{
++i;
printf("%d.\t\t\t\t", number_to_be_checked); //print if prime.
};
number_to_be_checked = number_to_be_checked + 1;
} while (number_to_be_checked <= upper_limit);
printf("\n pi(x) = %d \n", i);
//printf("pi function value is %f.", (i - 1) / (log(i - 1)));
float app;
app = upper_limit / (log(upper_limit));
float plot_value;
plot_value = (i) / app;
printf(" BETA FUNCTION VALUE ~ %f", plot_value);
return 0;
}
I can't figure out how to print next ten Perfect numbers.
Here's what I have got so far:
#include <stdio.h>
int main() {
int n, c = 1, d = 2, sum = 1;
printf("Enter any number \n");
scanf("%d", &n);
printf("The perfect numbers are:");
while(c <= 10) {
sum = 1;
d = 2;
while(d <= n / 2) { //perfect no
if(n % d == 0) {
sum = sum + d;
}
d++;
}
if(sum == n) {
printf("%d\n", n);
}
c++;
}
return 0;
}
The output I am currently receiving:
input: 2 (say)
output: 6
What I want:
input: 2
output:
6
28
496
8128
33550336
858986905
137438691328
2305843008139952128
2658455991569831744654692615953842176
191561942608236107294793378084303638130997321548169216
I have just started coding. Any help will be appreciated.
The integer overflow issue mentioned by several folks is significant, but secondary. Even if we fix your broken logic, and adjust it to handle larger, fixed sized integers:
#include <stdio.h>
int main() {
unsigned long long number;
printf("Enter any number \n");
scanf("%llu", &number);
printf("The perfect numbers are:\n");
int total = 0;
while (total < 10) {
unsigned long long sum = 1, divisor = 2;
while (divisor <= number / 2) {
if (number % divisor == 0) {
sum += divisor;
}
divisor++;
}
if (sum == number) {
printf("%llu\n", number);
total++;
}
number += 1;
}
return 0;
}
You still wouldn't get past the first four perfect numbers in any reasonable amount of time:
> ./a.out
Enter any number
2
The perfect numbers are:
6
28
496
8128
The primary issue is you're using a bad algorithm. Read about Mersenne primes, and their relationship to perfect numbers, as well as the Lucas-Lehmer test. This approach takes more thought, but surprisingly, not much more code. And will produce more results faster (though eventually bog down as well.)
You have to put the counter after you find a perfect number, so increasing c must happen in the if statement that checks the perfect number, like this:
if(sum==n){
printf("%d",n);
c++;
}
After this you need to increase the number, called n, like this:
n++;
and based on the numbers, #Jonathan Leffler is right, you should use proper variables.
Research, divide and conquer
Perfect numbers are of the form 2p − 1 * (2p − 1).
Code will need extended precision to form 191561942608236107294793378084303638130997321548169216
Increase efficiency
Iterating to <= n / 2 takes far too long. Iterate up to <= n / d
// while(d <= n / 2) {
while(d <= n / d) {
Sample improved code:
bool isprime(unsigned long long x) {
if (x > 3) {
if (x % 2 == 0) {
return false;
}
for (unsigned long t = 3; t <= x / t; t += 2) {
if (x % t == 0) {
return false;
}
}
return true;
}
return x >= 2;
}
Advanced: See Lucas–Lehmer primality test for quick prime test of Mersenne numbers
The below code works for all but the 10th perfect number as code must test for isprime(267 - 1) and I should leave something for OP to do.
static void buff_mul(char *buff, unsigned power_of_2) {
unsigned long long m = 1ull << power_of_2;
size_t len = strlen(buff);
unsigned long long carry = 0;
for (size_t i = len; i > 0;) {
i--;
unsigned long long sum = (buff[i] - '0') * m + carry;
buff[i] = sum % 10 + '0';
carry = sum / 10;
}
while (carry) {
memmove(buff + 1, buff, ++len);
buff[0] = carry % 10 + '0';
carry /= 10;
}
}
void print_perfext(unsigned p) {
// 2**(p-1) * (2**p - 1)
assert(p > 1 && p <= 164);
char buff[200] = "1";
buff_mul(buff, p);
buff[strlen(buff) - 1]--; // Decrement, take advantage that the LSDigit is never 0
buff_mul(buff, p - 1);
puts(buff);
fflush(stdout);
}
//unsigned next_prime(unsigned first_numeber_to_test_if_prime) {
#include <stdio.h>
int main() {
unsigned p = 0;
for (unsigned i = 0; i < 9; i++) {
// If p prime && 2**p − 1 is prime, then 2**(p − 1) * (2**p − 1) is a perfect number.
while (!isprime(p) || !isprime((1uLL << p) - 1))
p++;
printf("%2u ", p);
print_perfext(p);
p++;
}
return 0;
}
Output
2 6
3 28
5 496
7 8128
13 33550336
17 8589869056
19 137438691328
31 2305843008139952128
61 2658455991569831744654692615953842176
From output you wrote I belive that u want to show 10 first perfect numbers
Now u are only showing 6 because u show them from 1 to 10. In this range there is only 6.
I wrote sth like this:
#include <stdio.h>
int isperfect(int input) {
int sum = 0, value = input / 2;
do {
if (input % value == 0) sum += value;
value--;
} while (value);
if (input == sum) return 1;
else return 0;
}
int main() {
int i;
int count;
for (i = 2, count = 0; count < 4; i++) {
if (isperfect(i) == 1) {
count++;
printf("%d\n", i);
}
}
return 0;
}
But I don't recomend counting more than 4 because its gonna take too much time
I am trying to solve a problem that requires me to take a number. Use the % and / to take the rightmost number and sum the digits that are separated. Then tell see if the number is divisible by 9.
I have created a function that will separate the rightmost number and then I have tried to take that number and run it through a while loop. The problem that exist is, when I run the while loop. It creates an infinite loop or the output will not be printed.
#include <stdio.h>
int loopnum(int n);
int main(void)
{
int num;
int sum = 0;
int d = loopnum(num);
printf("Enter a number:\n");
scanf("%d", &num);
while (loopnum(num) > 0) {
printf("d = %d", d);
printf(",sum = %d\n", sum);
}
if (num % 9 == 0) {
printf("n = %d is divisible by 9\n", num);
}
else {
printf("n = %d is not divisible by 9\n", num);
}
return 0;
}
int loopnum(int n)
{
n = n % 10;
n = n / 10;
return n;
}
Enter a number:
9
n = 9 is divisible by 9
The result of this code is suppose to output d = "the digit" ,sum =
"digit + sum" and n = "digit" is divisible by 9. for example if I
input 9. The output would be d = 9, sum = 9.
The function does not make sense.
int loopnum(int n)
{
n = n % 10;
n = n / 10;
return n;
}
For example for n equal to 27 you will get
n = n % 10;
now n is equal to 7 and then
n = n / 10;
now n is equal to 0.
So for the number 27 the function returns 0.
And moreover inside the loop
while (loopnum(num) > 0) {
printf("d = %d", d);
printf(",sum = %d\n", sum);
}
neither num, nor d, nor sum is changed.
There is no great sense to define such a function except that it could itself to output intemediate sums and digits.
Without the function the program can look the following way.
#include <stdio.h>
int main(void)
{
while ( 1 )
{
const unsigned int Base = 10;
const unsigned int DIVISOR = 9;
printf( "Enter a non-negative number (0 - exit): " );
unsigned int n;
if ( scanf( "%u", &n ) != 1 || n == 0 ) break;
unsigned int sum = 0;
unsigned int tmp = n;
do
{
unsigned int digit = tmp % Base;
sum += digit;
printf( "d = %u, sum = %u\n", digit, sum );
} while ( tmp /= Base );
printf( "\nn = %u is %sdivisble by %u.\n\n",
n,
sum % DIVISOR == 0 ? "" : "not ", DIVISOR );
}
return 0;
}
Its ouutput might look like
Enter a non-negative number (0 - exit): 9
d = 9, sum = 9
n = 9 is divisble by 9.
Enter a non-negative number (0 - exit): 123456
d = 6, sum = 6
d = 5, sum = 11
d = 4, sum = 15
d = 3, sum = 18
d = 2, sum = 20
d = 1, sum = 21
n = 123456 is not divisble by 9.
Enter a non-negative number (0 - exit): 0
The loopnum code is wrong. It will always return zero and therefor the while will not loop.
int loopnum(int n)
{
n = n % 10; // After this n is a number between 0 and 9
n = n / 10; // Consequently, when you divide by 10 you'll end up with zero
return n;
}
Your design requires two things:
1) Return the remainder
2) Change n
To do that you need to pass a pointer to n.
Something like:
int loopnum(int *n)
{
int res = *n % 10;
*n = *n / 10;
return res;
}
int main(void)
{
int x = 123;
int sum = 0;
while(x) sum += loopnum(&x);
printf("%d\n", sum);
return 0;
}
Program to calculate the sum of five digits
This program is showing error in the compiler even though I think its factually correct
#include<stdio.h>
int main()
{
int i,a,num=32765,n;
int sum=0;
a=num%10;
n=num/10;
sum=sum+a;
for(i=0;i>4;i++)
{
a=n%10;
n=n/10;
sum=sum+a;
}
printf("the sum of five digits is %d", sum);
}
The loop in your code is never entered because i=0 and then you check if i>=3 which is never true.
You could use something like this:
int digit_sum(int num){
int sum=0;
while (num !=0){
sum += num%10;
num = num/10;
}
return sum;
}
int main()
{
int num = 12346;
/*
if (num <0) // add this block if negative number is posible
num = -num; // and its ok to change num or use some temp instead
*/
int sum = digit_sum(num);
printf("the sum of five digits is %d",sum);
return 0;
}
Or use recursion:
int digit_sum(int num){
if (num)
return num%10 + digit_sum(num/10);
}
Your loop is never entered because i=0 and cant be greater then 3!!! so the solution is:
int number=12345;
int total=0;
int remainder=0;
while(number>0){
remainder=number%10;
total=total+remainder;
number=number/10;
}
Your code is almost correct, just needed correct loop condition. Added comments so that you can see what is going on:
#include <stdio.h>
int main()
{
int i, a, num = 32765, n;
int sum = 0;
// extract 1st digit
a = num % 10; // a is 5 (% returns the remainder of the division)
n = num / 10; // n is 3276 (should be 3276.5, but int eats 0.5)
sum = sum + a; // sum is 5 which is (0 + 5)
// extract the remaining 4 digits
for (i = 0; i < 4; i++) // i is 0, 1, 2, 3
{
a = n % 10; // a is 6, 7, 2, 3
n = n / 10; // n is 327, 32, 3, 0
sum = sum + a; // sum is 11, 18, 20, 23
}
printf("the sum of five digits is %d", sum);
return 0;
}
https://ideone.com/EI9tgM
I get some homework, but i stack in it. Maybe you can help me. Task below.
Read the keyboard integer in the decimal system and establishment of a new system of numbers.
Output in the console number written in the new notation.
I made for 2 to 10 systems only and i can't make from 10 to 36. I tried to make in second loop something like this:
if ( result > 9 ) {
printf("%c", 55+number);
} else {
printf("%d", result);
}
my code:
#include <stdio.h>
int main() {
int number, base;
int i, result;
scanf("%d %d", &number, &base);
if ( number < base ) {
printf("%d\n", number);
} else {
for ( i = base; i <= number / base; i *= base );
for ( int j = i; j >= base; j /= base ) {
result = number / j;
printf("%d", result);
number = number % j;
}
printf("%d\n", number%base);
}
return 0;
}
else condition needs some changes:
1. value to digit conversion needs to apply to the inner loop and to the final printf("%d\n", number % base). Instead of adding in both places, simply make your loop run to j > 0, rather than j >= base and only use the last printf() for \n.
2. Rather than using a magic number 55 use result - 10 + 'A'. It easier to understand and does not depend on ASCII - (does depend on A, B, C ... being consecutive).
3. The rest is OK.
[edit]
#nos pointed out problem with if() condition.
So remove if ( number < base ) { ... else { and change for (i = base; to for (i = 1; making an even more simple solution.
// } else {
for (i = 1; i <= number / base; i *= base)
;
int j;
// for (j = i; j >= base; j /= base) {
for (j = i; j > 0; j /= base) {
result = number / j;
#if 1
if (result > 9) {
// printf("%c", 55 + result);
printf("%c", result - 10 + 'A');
} else {
printf("%d", result);
}
#else
printf("%d", result);
#endif
number = number % j;
}
printf("\n");
// }
int number, base;
scanf("%d %d", &number, &base);
int divisor = base;
while (divisor <= number)
divisor *= base;
while (divisor != 1) {
divisor /= base;
int digit = number / divisor;
number -= digit * divisor;
printf("%c", digit <= 9 ? digit + '0' : digit + 'A' - 10);
}
printf("\n");
return 0;
Caveat: Undefined behavior for numbers greater than ~200000000.
You're on the right track and are very close to the answer. Your program is printing the resulting digits in two places.
I suggest making a single function to output the digits and using it in both places:
void print_digit(int number) {
// your code here
}
You can add characters and integers, so try something more like:
'A' + // some int value
On the other hand, should one like a solution that does not under/overflow, handles all INT_MIN to INT_MAX, no UB, only enter INT_MIN <= number <= INT_MAX, 2 <= base <= 36, and you don't mind recursion.
#include <stdio.h>
#include <stdlib.h>
void print_digit(int x, int base) {
int quot, rem;
quot = x/base;
if (quot) {
print_digit(quot, base);
}
rem = abs(x%base);
if (rem > 9) {
printf("%c", rem - 10 + 'A');
} else {
printf("%d", rem);
}
}
int main() {
int number, base;
scanf("%d %d", &number, &base);
if (number < 0) {
printf("-");
}
print_digit(number, base);
printf("\n");
return 0;
}