Program to reverse a number without using an array - c

This is the code that I used. It works perfectly, but I don't understand why it works. I just kept changing my original logic until I started using -1 in the counter loop.
#include<stdio.h>
#include<math.h>
int main(){
int number, reverse, sum =0;
scanf("%d", &number);
int temp = number;
int ctr;
for(ctr = -1; temp!=0; ctr++)
temp = temp/10;
while(number)
{
sum = sum + (number%10 * (pow(10, ctr--)));
number = number/10;
}
printf("%d", sum);
return 0;
}

same basic math but so much easier to understand:
unsigned int number = 123456789;
unsigned int reversed = 0;
do {
reversed *= 10;
reversed += number % 10;
number /= 10;
} while (number > 0);

Although this is kind of awkward to explain the logic of the code that you wrote it yourself, I understood the logic behind it.
Indeed, I was looking for a solution to solve this problem: How to reverse any positive integer without using arrays or indexed variables to which your code was the solution I was looking for.
The logic of your programme is like this:
you first count the digits of the given number in the FOR-loop in the shortest possible way. you need this because you have to 10-power each remainder up to digits of the given number in the next WHILE-loop and you store/add the result of this each time in the variable named SUM. The final result of this would be the whole integer to be reversed.
PS1:
You do not need the variable named REVERSE. Just drop it or replace SUM with it.
PS2:
You really do not need to go that long way to do this. Here's another shorter version:
#include <stdio.h>
void main (void){
unsigned short int uNum, nReversed;
puts ("Enter a positive integer number: ");
scanf ("%hu", &uNum);
while (uNum != 0){
nReversed = uNum%10 + nReversed*10 ;
uNum /= 10;
}
printf ("\n\n\nThat is %d", nReversed);
}

Related

Sum digits of number [duplicate]

This question already has answers here:
Find the sum of digits of a number(in c)
(6 answers)
Closed 2 years ago.
Hello i need problem with this task in C language. If anyone had a similar problem it would help me.
The task is:
Write a program that loads the numbers a and b (a <b), then finds and prints the numbers from the segment of [a, b] and prints the sum of the digits of each number.
I wrote for three issues, for example:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n1,n2,sum=0,a,b,k,n3;
scanf("%d",&a);
scanf("%d",&b);
for(k=a;k<=b;k++)
{
n1=k%10;
n2=(k/10)%10;
n3=k/100;
sum=n1+n2+n3;
printf("%d\n",sum);
}
}
The problem arises when I enter a larger than three-digit number, how to make for any number, no matter if it is two-digit, three-digit, four-digit ...
Well the way you solve this issue depends on the exact requirements. Given that you only have ints here I would use the following though it is by no meand production code
int main() {
int a = whatever;
int b = whatever;
char* a_as_s = itoa(a);
char* b_as_s = itoa(b);
int sum_of_a = 0;
int sum_of_b = 0;
for(int i = 0; a_as_s[i]; i++)
sum_of_a += atoi(a_as_s[i]);
for(int i = 0; b_as_s[i]; i++)
sum_of_b += atoi(b_as_s[i]);
}
That should calculate the sum of digits for arbirary lengths - the rest of your code seems fine
You've already solved the iterating part so as people have suggested in the comments all you need now is a way to sum the digits of an arbitrary integer. I've modified your solution with my take on the problem. I'm pretty sure there is a more elegant/efficient way to do this, so I'd suggest you also check out the links people have provided in the comments. Anyhow here is my take:
#include <stdio.h>
int maxPowOf10(int num)
{
int divisor = 1;
for(;;)
{
if(num / divisor == 0)
{
break;
}
divisor *= 10;
}
return divisor / 10;
}
int sumOfDigits(int num)
{
int sum = 0;
for(int divisor = maxPowOf10(num); divisor >= 1; divisor /= 10)
{
int tmp = num / divisor;
sum += tmp;
num -= tmp * divisor;
}
return sum;
}
int main()
{
int n1,n2,sum=0,a,b,k,n3;
printf("Insert a: ");
scanf("%d",&a);
printf("Insert b: ");
scanf("%d",&b);
printf("Result\n");
for(k=a;k<=b;k++)
{
sum = sumOfDigits(k);
printf("number: %d sum of its digits: %d\n", k, sum);
}
return 0;
}
The approach is fairly straightforward. To find the sum of the digits, first you determine what is the largest power of 10 that still features in the number. Once that is found we can just divide by the largest power of 10 and add the result to sum. The trick is that, after that, we have to remove the part of the number that is described by the decimal place we are at. So we don't count it again. Then, you keep repeating the process for ever decreasing powers of 10. In the end you have the complete sum.
To illustrate this on 152 for example:
a) The largest power of 10 in 152 is 100.
b1) We divide 152 by 100 and get 1. We add 1 to sum. We also decrease the number to 52 (152 - 100)
b2) We divide 52 by 10 and get 5. We add 5 to sum. We decrease the number to 2 (52 - 50).
b3) We divide 2 by 1 and get 2. We add 2 to sum. We decrease the number to 0 (2 - 2).
Point a describes the method maxPowOf10
Point b describes the method sumOfDigits

Finding the largest palindrome number

Firstly I'm a new coder. I am trying to find the largest palindrome made from the product of two-3 digit integer which I found on Project Euler-Problem 4. I've written some code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n;
int i,num,k;
int sum, j=1, palindrome = 0;
num = 999*999;
i = n = num;
while(!palindrome){
for(i=999*999; i>10000; i--){
sum = 0;
num = i;
while(num!=0){
k = num%10;
sum = sum*10 + k;
num /= 10;
}
if(i==sum){
printf("\nThe Number is a palindrome ");
palindrome = 1;
break;
}
}
}
printf("%d", sum);
return 0;
}
But it seems to give me the wrong result.It gives the result 997799. I searched in the internet, the result should be 906609. Any help would be grateful.
if(n==sum){
What is n? You initialize it to 999*999 at the top of the program and then never change it again. Perhaps you mean i?
if(i==sum){
Now the program prints 997799, a proper palindrome.
Note, though, that there's no check that sum is the product of two three-digit numbers. Your current approach of starting at a high number and decrementing i by 1 each iteration won't really work. You really need two variables and two loops to iterate over the two three-digit numbers.
But two loops will make it noticeably more difficult to find the largest palindrome. Oh dear.
for (int a = 100; a <= 999; a++) {
for (int b = 100; b <= 999; b++) {
int n = a * b;
// n is the product of two three digit numbers.
// check: is it a palindrome?
// check: is it the *largest* palindrome?
}
}

Break a number down int array and get factorial of each number - C programming

I apologize in advance for the length of the code and how tedious it may be to follow. I am trying to break a number down into individual digits and get the factorial of each one. I have successfully done that (with the help of paxdiablo) but I want to do this all the way from 99999 to 0. In order to do that I have placed all of the code in a loop starting indx at 99999 and decreasing value until it reaches 1. The reason I am trying to do this is because I need to compare the sum of the factorial of each individual digit to the number and if they are equal then I have a match. The program runs and the first run for the number 99999 works perfectly fine but the next loop SHOULD be 99998 and do the exact same thing but instead the next number is 4. I have no idea why it would do this. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
int indx;
int fact = 1;
int individualDigit[50];
int length;
for(indx = 99999; indx > 0; indx--)
{
num = indx;
for (length = 0; num > 0; length++, num /= 10)
{
individualDigit[length] = num % 10;
}
printf ("Digit count = %d, digits =", length);
for (indx = length - 1; indx >= 0; indx--)
{
printf (" %d", individualDigit[indx]);
}
for (indx = 0; indx < length; indx++)
{
while (individualDigit[indx] > 0)
{
fact = fact * individualDigit[indx];
individualDigit[indx]--;
}
printf("\n%d ", fact);
fact = 1;
}
printf("\n");
}
return 0;
}
The value in "indx" is being used by multiple for loops. The line
for (indx = 0; indx < length; indx++)
increments indx back up to 4, which is the value used by your outer loop. Just use some new variables to count the different loops
This seems like a homework question and your code quality seems to confirm that so I'm hesitant to write you actual code but I'll give you a few pointers.
As #Cody Braun said above your index variable is getting overwritten in line 23 where you calculate the factorial.
There is a much more efficient way to calculate factorials using dynamic programming
I don't know if you just didn't want to do it in the post but learning how to properly format your code will help you catch these errors quicker and keep yourself form making them. As well as make it easier for others to read your code.
Cheers

Tricky and confusing C program about divisor sum and perfect numbers

The assignment is :
Write a program that calculates the sum of the divisors of a number from input.
A number is considered perfect if the sum of it's divisiors equal the number (ex: 6 = 1+2+3 ;28 = 1 + 2 + 4 + 7 +14).
Another definition:
a perfect number is a number that is half the sum of all of its positive divisors (including itself)
Generate the first k perfect numbers (k<150).
The main problem with this is that it's confusing the two asking points don't really relate.
In this program i calculated the sum of divisors of an entered number, but i don't know how to relate it with the second point (Generate the first k perfect numbers (k<150)).
#include <stdio.h>
#include <stdlib.h>
main()
{
int x,i,y,div,suma,k;
printf("Introduceti numarul\n"); \\enter the number
scanf("%d",&x);
suma=0; \\sum is 0
for(i=1;i<=x;i++)
{
if(x%i==0)
suma=suma+i; \\sum=sum+i;
}
printf("Suma divizorilor naturali este: %d\n",suma); \\the sum of the divisors is
for(k=1;k<150;k++) \\ bad part
{
if (x==suma)
printf("%d",k);
}
}
Suppose you have a function which can tell whether a given integer is perfect or not:
int isPerfect(int);
(function body not shown)
Now your main program will look like:
int candidate;
int perfectNumbers;
for(candidate = 1, perfectNumbers = 0; perfectNumbers < 150; candidate++) {
if (isPerfect(candidate)) {
printf("Number %d is perfect\n", candidate);
perfectNumbers++;
}
}
EDIT
For the same program without functions:
int candidate;
int perfectNumbers;
for(candidate = 1, perfectNumbers = 0; perfectNumbers < 150; candidate++) {
[... here your algorithm to compute the sum of the divisors of "candidate" ...]
if (candidate*2 == sum_of_divisors) {
printf("Number %d is perfect\n", candidate);
perfectNumbers++;
}
}
EDIT2: Just a note on perfect numbers
As noted in the comments section below, perfect numbers are very rare, only 48th of them are known as of 2014. The sequence (A000396) also grows very fast: using 64-bit integers you'll be able to compute up to the 8th perfect number (which happen to be 2,305,843,008,139,952,128). In this case the variable candidate will wrap around and start "finding" "new" perfect numbers from the beginning (until 150 of them are found: actually 19 repetitions of the only 8 findable in 64-bit integers). Note though that your algorithm must not choke on a candidate equals to 0 or to negative numbers (only to 0 if you declare candidate as unsigned int).
I am interpreting the question to mean generate all numbers under 150 that could are perfect numbers.
Therefore, if your program works for calculating perfect numbers, you keep calculating them until the starting number is >= 150.
Hope that makes sense.
Well, here's my solution ..
First, you have to make a reliable way of getting divisors.Here's a function I made for that:
size_t
getdivisors(num, divisors)
long long num;
long long *divisors;
{
size_t divs = 0;
for(long long i = num; i > 0; --i)
if (num%i == 0)
divisors[divs++] = i;
return divs;
}
Second, you need to check if the number's divisors match the perfect number's divisors properties (the sum of them is half the number).
Here's a second function for that:
bool
isperfect(num)
long long num;
{
long long divisors[num/2+1];
size_t divs = getdivisors(num, divisors);
if (divs == 0)
return false;
long long n = 0;
for(int i = 1; i < divs; ++i)
n += divisors[i];
return (n == num);
}
Now, from your question, I think you need to print all perfect numbers less than 150, right ?
See this:
int
main(argc, argv)
int argc;
char ** argv;
{
for(int i = 1; i < 150; ++i)
if (isperfect(i))
printf("%d is perfect.\n", i);
return 0;
}
I hope that answers your question ..

Long precise numbers in C?

I am making a program that prints the first 100 Lucas numbers(they are like Fibonacci), but the last few numbers don't fit in unsigned long long int. I tried using long double, but it isn't precise and I get some differences with what I am supposed to get.
This is a homework task and my teacher specifically specified we do not need to use any other library than stdio.h.
I tried making a method that adds strings as numbers, but it is way beyond out experience and I sincerely doubt that is what we have to do.
With imprecisions it looks something like this:
#include <stdio.h>
int main()
{
long double firstNumber = 2;
long double secondNumber = 1;
long double thirdNumber;
int i;
for (i = 2; i <= 100; i += 1)
{
thirdNumber = secondNumber + firstNumber;
firstNumber = secondNumber;
secondNumber = thirdNumber;
printf("%Lf, ", thirdNumber);
}
return 0;
}
It looks like all you need is addition. I see three ways you can go about this.
If you weren't forbidden from using libraries then you'd use one of the many bigint libraries commonly available.
Implement a string-based adder. You'd basically implement the addition method you learned in 3rd grade.
As a hack, if your largest number fits in roughly two unsigned long long ints then you can split your number up into Most Significant Digits and Least Significant Digits. I'd go this route.
I used below to store really large numbers in an array. Pasting the code below with some comments. Hope it helps.
#include<stdio.h>
int main()
{
int t;
int a[200]; //array will have the capacity to store 200 digits.
int n,i,j,temp,m,x;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
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 in position j
temp = x/10; //Contains the carry value that will be stored on later indexes
}
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--) //printing answer
printf("%d",a[i]);
printf("\n");
}
return 0;
}

Resources