I am trying to generate armstrong number to nth number.So,I have written a code for that,but it is not working.Everytime I input a number like 999 or 10000,it return only 0....can anyone please help me to find out what's wrong with this code:
#include <stdio.h>
#include <math.h>
int main()
{
double remainder,n=0;
int number,sum = 0,q,x,count;
printf("Enter an integer upto which you want to find armstrong numbers:");
scanf("%d",&number);
printf("\nFollowing armstrong numbers are found from 1 to %d\n",number);
for( count = 1 ; count <= number ; count++ )
{
q = count;
x = count;
for(;x != 0;)
{
x =x / 10;
n = n + 1;
}
while(q != 0)
{
remainder = q % 10;
sum = sum +(pow(remainder,n));
q = q / 10;
}
if ( count == sum ){
printf("%d\n", count);
}
sum = 0;
}
return 0;
}
You have to initialize n to zero inside the loop for count. And take care of proper rounding of the result of pow by for example adding 0.5 to it.
Related
#include <stdio.h>
#include <stdlib.h>
#define TEN 10
int main ()
{
int number = 0;
int digit = 0;
int last_digit = 0;
int digit_sum = 0;
int i = 0;
while (i == 0)
{
printf("Please Enter A Positive Number! \n"); //explaining
scanf("%d",&number);
if (number > 0)
{
i++;
}
}
while (number > 0)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
if (last_digit != digit) //comparing digits
{
last_digit = digit;
digit_sum += digit;
}
}
printf("The Sum Of The Digits Is : %d",digit_sum);
return 0;
}
the code will divide the number into digits and check if there are duped digits, in case there are, only one of them will be calculated for exmple: 3211
3+2+1, but my problem is thats the code wont work with numbers like 31211 Im thankful for any kind of help.
The code doesn't work because there is no guarantee that duplicate's will appear consecutive manner. your code handles that not the other ways. That's why it fails.
A simple solution would be to consider a 10 element array where you will keep count of which element appeared and which didn't.
The idea is to map the digits to the array indices of the 10 element array. Intialized with 0.
...
int digitAppeared[10]={0};
while (number)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
digit_sum += (1 - digitAppeared[digit]) * digit;
digitAppeared[digit] = 1;
}
...
To give you a clear idea this line basically checks whether the element appeared or not and as per the result it will add the digit.
If digit D appeared then digitAppeared[D]=1
and if it didn't then digitAppeared[D]=0.
We will add it to digitsum if it appears first time. That's why the (1-digitAppeared[D]) will tell us whether to add it or not.
digit_sum += (1 - digitAppeared[digit]) * digit;
Convert the number to string use itoa() . sort it and then walk through it , looking for unique number and do your calculation
You can mark which digits were already added by using setting logical flags as represented by done in program below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TEN 10
int main ()
{
int number = 0;
int digit = 0;
int last_digit = 0;
int digit_sum = 0;
int i = 0;
int done[10];
while (i == 0)
{
printf("Please Enter A Positive Number! \n"); //explaining
scanf("%d",&number);
if (number > 0)
{
i++;
}
}
memset(done,0,sizeof(done));
while (number > 0)
{
digit = number % TEN; //breaking number into digits
number /= TEN;
if(done[digit] == 0)
{
digit_sum += digit;
done[digit] = 1;
}
}
printf("The Sum Of The Digits Is : %d",digit_sum);
return 0;
}
I need to write a C program which will read a number (in base 10) from user input and output it in any base which is a power of 2. The calculations have to be performed in one function, to_base_n, which takes the parameters num and base and prints the number in the respective base. As a validation check, the program also checks if the base is a power of two with the isPowerofTwo function.
The way the conversion is carried out is by means of long division which carries out the logic in the pseudocode below:
void to_base_n(int x, int n){
int r, i = 0
int digits[16]
while (x ≠ 0){
r = x mod n
x = x / n
digits[i] = r
i++
}
for (i = 0, i < 15, i++)
print digits[i]
}
Which I believe is arithmetically sound. But when I try to, for example, convert 82000 to base 4, I get the following output:
The large digits appearing are even bigger than num itself, so I figured the modulus cannot be entering the array properly (because ∀{x,n}; x mod n < x). I can't seem to find what's wrong with it. The full code is listed below.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
bool isPowerofTwo(int);
void to_base_n(int, int);
int main(){
//Variables
int num, base;
//Prompt
printf("Please enter a number in base 10: ");
scanf("%d", &num);
printf("Please enter a base (2^n) to convert it to: ");
scanf("%d", &base);
//Precaution
while(!isPowerofTwo(base)){
printf("That number is not a power of 2. Please try again: ");;
scanf("%d", &base);
}
if(isPowerofTwo(base)){
//Output
printf("The number %d (base 10) is equivalent to ", num);
to_base_n(num, base);
printf(" (base %d).", base);
}
//Return Statement
return 0;
}
//Checks if Base is a Power of Two
bool isPowerofTwo(int base){
while((base % 2 == 0) && base > 1){
base = base / 2;
if(base == 1){
return true;
break;
}
}
return false;
}
//to_base_n
void to_base_n(int x, int n){
int r, i = 0;
int digits[16];
while(x != 0){
r = x % n;
x = x / n;
digits[i] = r;
i++;
}
for(i = 0; i < 15; i++)
printf("%d|",digits[i]);
}
Can anyone help explain what's wrong with it?
The number 82000 in base 4 would be:
110001100
Which is exacly what you get. Your mistake is that:
They are printed backwards.
You are printing more digits than you should, so you print garbage.
You ignore the number of digits extracted with your pseudo code, so you print uninitialised elements of the array.
for (i = 0, i < 15, i++)
print digits[i]
And they are printed in reverse order. I suggest changing it to this
for (i = i - 1, i >= 0, i--)
print digits[i]
and as C code in your function
for(i = i - 1; i >= 0; i--)
printf("%d|",digits[i]);
A twin prime is a prime number that is exactly two larger than the largest prime number that is smaller than it. For example, 7 is a twin prime because it is exactly two larger than 5. But 17 is not a twin prime because the largest prime less than 17 is 13.
My logic for this program is as follows:
*ask number of twin primes that want to be found
*loop until desired number of twin primes are found
*loop numbers 2 - 1million (declared as variable j)
*check if that number 'j' is prime - if so flag it
*if 'j' is not flagged, subtract 2 from 'j' (call that new number 'TPcheck')
*Check if 'TPcheck' is a prime, if so, print 'TPcheck' and the first number 'j'
When I run this program, I enter the number of twin primes to be found, but it just continues to run, and doesn't print anything on the screen. I think that the problem may have something to do with the order of the loops and if statements(or maybe the way that they are nested), but I have tried a ton of different ways and nothing has worked.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 2, count = 0, TPcheck, j, k, flag;
int numberofTwinPrimes;
printf("Enter how many twin primes you want to find");
scanf("%d", &numberofTwinPrimes);
while(count < numberofTwinPrimes)
{
for(j = 2; j <= 1000000; ++j)
{ for(i = 2; i < j; ++i)
{
if(j%i == 0)
{
flag = 1;
continue;
}
if(flag == 0)
{
TPcheck = j - 2;
for(k = 2; k < TPcheck; ++k)
{
if(TPcheck%k == 0)
{
flag = 1;
continue;
}
if(flag == 0)
{
printf("%d\t %d\t", TPcheck, j);
count++;
}
}
}
}
}
}
return 0;
}
I think your code can be simplified quite a bit.
Define a function that simply returns whether a number is a prime number or not.
Use that in a loop using a very simple logic.
Here's a working version.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int isPrime(int n)
{
int stop = 0;
int i = 0;
// Special case for 3.
if ( n == 3 )
{
return 1;
}
// If n is not divisible by numbers up to sqrt(n),
// then, n is a prime number.
stop = (int)(sqrt(n));
// We can start at 3 and increment by 2
// There is no point dividing by even numbers.
for ( i = 3; i <= stop; i +=2 )
{
if ( n%i == 0 )
{
// It is not a prime number.
return 0;
}
}
// Checked divisibility by all numbers up to sqrt(n)
// This is a prime number.
return 1;
}
int main()
{
int i = 0;
int count = 0;
int numberofTwinPrimes;
printf("Enter how many twin primes you want to find: ");
scanf("%d", &numberofTwinPrimes);
// Start checking at 3 and increment by 2.
// There is no point checking even numbers.
// When we find the required number of twin primes, stop.
for(i = 3; i <= 1000000 && count < numberofTwinPrimes; i += 2 )
{
if ( isPrime(i) && isPrime(i+2) )
{
++count;
printf("%d\t %d\n", i, i+2);
}
}
return 0;
}
Here's the output when numberOfTwinPrimes is 10.
3 5
5 7
11 13
17 19
29 31
41 43
59 61
71 73
101 103
107 109
This isPrime() function is faster than Fumu's suggestion:
/* function isPrime returns True if argument is prime number. */
boolean isPrime(int aNumber)
{
int i;
int limit;
/* Numbers < 2 */
if(aNumber < 2) { return False; }
/* Even numbers. */
if (aNumber % 2 == 0) { return aNumber == 2; }
/* Odd numbers. */
/* Only need to check odd divisors as far as the square root. */
limit = (int)(sqrt(aNumber));
for (i = 3; i <= limit; i += 2)
{
if( aNumber % i == 0) { return False; }
}
/* Only prime numbers make it this far. */
return True;
}
Two is the only even prime, so all even numbers can be dealt with very quickly. Odd numbers only need to be tested with odd divisors less than or equal to the square root of the number: 9 = 3 * 3
There are faster methods, but they require construction of a table of primes. For your program, something like this appears to be sufficient.
Your code for checking a number is prime or not is not correct.
You should check the number never be divided any numbers less than the number.
Code of a function for checking a numer is prime or not is as follows:
/* function isPrime returns True if argument is prime number. */
boolean isPrime(int aNumber)
{
int i;
if(aNumber < 2) { return False; }
else if (aNumber==2) {return True;}
for i=2 to aNumber-1
{
if((aNumber%i) == 0){
return False;
}
}
return True;
}
I hope this give you some useful idea.
I have a problem, then given some input number n, we have to check whether the no is factorial of some other no or not.
INPUT 24, OUTPUT true
INPUT 25, OUTPUT false
I have written the following program for it:-
int factorial(int num1)
{
if(num1 > 1)
{
return num1* factorial(num1-1) ;
}
else
{
return 1 ;
}
}
int is_factorial(int num2)
{
int fact = 0 ;
int i = 0 ;
while(fact < num2)
{
fact = factorial(i) ;
i++ ;
}
if(fact == num2)
{
return 0 ;
}
else
{
return -1;
}
}
Both these functions, seem to work correctly.
When we supply them for large inputs repeatedly, then the is_factorial will be repeatedly calling factorial which will be really a waste of time.
I have also tried maintaining a table for factorials
So, my question, is there some more efficient way to check whether a number is factorial or not?
It is wasteful calculating factorials continuously like that since you're duplicating the work done in x! when you do (x+1)!, (x+2)! and so on.
One approach is to maintain a list of factorials within a given range (such as all 64-bit unsigned factorials) and just compare it with that. Given how fast factorials increase in value, that list won't be very big. In fact, here's a C meta-program that actually generates the function for you:
#include <stdio.h>
int main (void) {
unsigned long long last = 1ULL, current = 2ULL, mult = 2ULL;
size_t szOut;
puts ("int isFactorial (unsigned long long num) {");
puts (" static const unsigned long long arr[] = {");
szOut = printf (" %lluULL,", last);
while (current / mult == last) {
if (szOut > 50)
szOut = printf ("\n ") - 1;
szOut += printf (" %lluULL,", current);
last = current;
current *= ++mult;
}
puts ("\n };");
puts (" static const size_t len = sizeof (arr) / sizeof (*arr);");
puts (" for (size_t idx = 0; idx < len; idx++)");
puts (" if (arr[idx] == num)");
puts (" return 1;");
puts (" return 0;");
puts ("}");
return 0;
}
When you run that, you get the function:
int isFactorial (unsigned long long num) {
static const unsigned long long arr[] = {
1ULL, 2ULL, 6ULL, 24ULL, 120ULL, 720ULL, 5040ULL,
40320ULL, 362880ULL, 3628800ULL, 39916800ULL,
479001600ULL, 6227020800ULL, 87178291200ULL,
1307674368000ULL, 20922789888000ULL, 355687428096000ULL,
6402373705728000ULL, 121645100408832000ULL,
2432902008176640000ULL,
};
static const size_t len = sizeof (arr) / sizeof (*arr);
for (size_t idx = 0; idx < len; idx++)
if (arr[idx] == num)
return 1;
return 0;
}
which is quite short and efficient, even for the 64-bit factorials.
If you're after a purely programmatic method (with no lookup tables), you can use the property that a factorial number is:
1 x 2 x 3 x 4 x ... x (n-1) x n
for some value of n.
Hence you can simply start dividing your test number by 2, then 3 then 4 and so on. One of two things will happen.
First, you may get a non-integral result in which case it wasn't a factorial.
Second, you may end up with 1 from the division, in which case it was a factorial.
Assuming your divisions are integral, the following code would be a good starting point:
int isFactorial (unsigned long long num) {
unsigned long long currDiv = 2ULL;
while (num != 1ULL) {
if ((num % currDiv) != 0)
return 0;
num /= currDiv;
currDiv++;
}
return 1;
}
However, for efficiency, the best option is probably the first one. Move the cost of calculation to the build phase rather than at runtime. This is a standard trick in cases where the cost of calculation is significant compared to a table lookup.
You could even make it even mode efficient by using a binary search of the lookup table but that's possibly not necessary given there are only twenty elements in it.
If the number is a factorial, then its factors are 1..n for some n.
Assuming n is an integer variable, we can do the following :
int findFactNum(int test){
for(int i=1, int sum=1; sum <= test; i++){
sum *= i; //Increment factorial number
if(sum == test)
return i; //Factorial of i
}
return 0; // factorial not found
}
now pass the number 24 to this function block and it should work. This function returns the number whose factorial you just passed.
You can speed up at least half of the cases by making a simple check if the number is odd or even (use %2). No odd number (barring 1) can be the factorial of any other number
#include<stdio.h>
main()
{
float i,a;
scanf("%f",&a);
for(i=2;a>1;i++)
a/=i;
if(a==1)
printf("it is a factorial");
else
printf("not a factorial");
}
You can create an array which contains factorial list:
like in the code below I created an array containing factorials up to 20.
now you just have to input the number and check whether it is there in the array or not..
#include <stdio.h>
int main()
{
int b[19];
int i, j = 0;
int k, l;
/*writing factorials*/
for (i = 0; i <= 19; i++) {
k = i + 1;
b[i] = factorial(k);
}
printf("enter a number\n");
scanf("%d", &l);
for (j = 0; j <= 19; j++) {
if (l == b[j]) {
printf("given number is a factorial of %d\n", j + 1);
}
if (j == 19 && l != b[j]) {
printf("given number is not a factorial number\n");
}
}
}
int factorial(int a)
{
int i;
int facto = 1;
for (i = 1; i <= a; i++) {
facto = facto * i;
}
return facto;
}
public long generateFactorial(int num){
if(num==0 || num==1){
return 1;
} else{
return num*generateFactorial(num-1);
}
}
public int getOriginalNum(long num){
List<Integer> factors=new LinkedList<>(); //This is list of all factors of num
List<Integer> factors2=new LinkedList<>(); //List of all Factorial factors for eg: (1,2,3,4,5) for 120 (=5!)
int origin=1; //number representing the root of Factorial value ( for eg origin=5 if num=120)
for(int i=1;i<=num;i++){
if(num%i==0){
factors.add(i); //it will add all factors of num including 1 and num
}
}
/*
* amoong "factors" we need to find "Factorial factors for eg: (1,2,3,4,5) for 120"
* for that create new list factors2
* */
for (int i=1;i<factors.size();i++) {
if((factors.get(i))-(factors.get(i-1))==1){
/*
* 120 = 5! =5*4*3*2*1*1 (1!=1 and 0!=1 ..hence 2 times 1)
* 720 = 6! =6*5*4*3*2*1*1
* 5040 = 7! = 7*6*5*4*3*2*1*1
* 3628800 = 10! =10*9*8*7*6*5*4*3*2*1*1
* ... and so on
*
* in all cases any 2 succeding factors inf list having diff=1
* for eg: for 5 : (5-4=1)(4-3=1)(3-2=1)(2-1=1)(1-0=1) Hence difference=1 in each case
* */
factors2.add(i); //in such case add factors from 1st list " factors " to " factors2"
} else break;
//else if(this diff>1) it is not factorial number hence break
//Now last element in the list is largest num and ROOT of Factorial
}
for(Integer integer:factors2){
System.out.print(" "+integer);
}
System.out.println();
if(generateFactorial(factors2.get(factors2.size()-1))==num){ //last element is at "factors2.size()-1"
origin=factors2.get(factors2.size()-1);
}
return origin;
/*
* Above logic works only for 5! but not other numbers ??
* */
}
i am doing one of the simple programin C, sum of digits of 5 digit number.Though i had done it using a simple function but i need to do it with recursion also.I had read many solution on net regarding this problem using recursion and had implemented one of mine.But that is giving error and i cant figure out what mesh i am doing in my algo.
#include<stdio.h>
int sum5(int x); //function for sum of digits of 5 digit number
int main()
{
int x;
int result;
printf("Enter a 5 digit number : ");
scanf("%d",&x);
printf("Number entered by you is %d",x);
result = sum5(x);
printf("Sum of digits of 5 digit number is = %d",&result);
return 0;
}
int sum5(int x)
{
int r;
int sum=0;
if(x!=0){
r=x%10;
sum=sum+r;
x=x-r; //doing this so that 0 come in the last and on diving it by 10, one digit will be removed.
sum5(x/10);
}
return sum;
}
but after its execution i am getting wrong result.It is dumping some anonymous value on the output.
Also, your sum5 function is incorrect. You have to add the value of sum5 to the sum variable of the caller function.
int sum5(int x)
{
int r;
int sum = 0;
if (x != 0) {
r = x % 10;
sum = r;
//x = x - r; - this isn't required. integer division will floor x
sum += sum5(x / 10);
}
return sum;
}
This is incorrect as it is printing the address of result and not its value:
printf("Sum of digits of 5 digit number is = %d",&result);
Change to:
printf("Sum of digits of 5 digit number is = %d", result);
Always check the result of scanf() to ensure a valid value was read:
/* Returns number of assignments made. */
if (scanf("%d", &x) == 1 && x > 9999 && x < 100000)
{
}
Plus the error in the implementation of sum5() as pointed out by Osiris
.