Prime Palindrome Logic Efficiency - c

I wrote a code to get first 1000 prime palindromes ,though my logic is correct ,I dont seem to be getting first 1000 prime palindromes ,I am getting some 113 Prime Palindromes and after that I don't get any . I think this is because my logic is not efficient enough ,that is why it is taking so much time to compile ,but I already tried three different methods and everytime the Runtime is getting stuck after the 113th Prime Palindrome Number .
Can anyone explain why exactly I am getting this problem ,is it because the code is not efficient?
/* Program to find the first 1000 prime palindromes */
#include<stdio.h>
#include<math.h>
int prime(long int n)
{
int i,check=0;
if(n!=2 && n%2==0)
return 0;
if(n==2 || n==3)
return 1;
for(i=3;i<n/2;i=i+2)
if(n%i==0)
check++;
if(check==0)
return 1;
else
return 0;
}
/*long int reverse_number(long int n,long int partial)
{
if(n==0)
return partial;
else
return reverse_number(n/10,partial*10 + n%10);
}*/
int palindrome(long int n)
{
long int reverse = 0;
long int n_copy = n;
int rem;
while(n_copy!=0)
{
rem = n_copy%10;
reverse = reverse*10;
reverse = reverse + rem;
n_copy = n_copy/10;
}
if(reverse==n)
return 1;
else
return 0;
}
int main()
{
long int i;
int count=5,digits;
printf("The 1000 prime palindromes are: \n");
printf("1. 2\n2. 3\n3. 5\n4. 7\n");
for(i=11;;i=i+2)
{
if(prime(i))
{
if(palindrome(i))
{
printf("%d. %ld\n",count,i);
count++;
}
/*if(reverse_number(i,0)==i)
{
printf("%d. %ld\n",count,i);
count++;
}*/
}
if(count==50)
break;
}
printf("\n\n");
return 0;
}

Let me quote my imperative programming professor here: "You can check whether the number is a prime and a palindrome, or check whether it's a palindrome and a prime..."
Also, you're breaking the loop when count is 50, which I suppose you want to do when it's 1000.
Without editing the prime and palindrome functions, besides the order in which they're called, my PC stops finding more after 781 9989899.

Related

C code to find number of digits in integer is not working as per.suggest modifications

here is the link to the file(google docs link) containing my code -
#include<stdio.h>
int len(int);
void main()
{
int n,p;
printf("enter number");
scanf("%d",&n);
p=len(n);
printf("length of entered number is %d",p);
}
int len(int num)
{
int i,c,b;
for(i=1;i<=50;i++){
b=10*i;
if(num<b) {
return(i);
break;
}
}
}
Computing b=10*i; makes no logical sense. Did you want to raise 10 to a given power?
The normal way of solving this problem is to repeatedly divide by 10 until 0 is reached (using integer arithmetic), and count the number of divisions made. That is the number of digits in the original number. This method is also not vulnerable to integer overflow:
unsigned digits = 0;
for (; num /= 10; ++digits);
return digits;
int len(int num){
int i = 0;
if(num == 0)
return 1;
while(num!=0){
num = num / 10;
i++;
}
return i;
}
here we divide num by 10 until it reaches 0, and each time loop executes we increment the count i++
frontmatter i am not able to recognize your answer but i think this following code is helpful as per your title.
#include<stdio.h>
#include<conio.h>
void main()
{
char a[50000];
int i,c=0;
printf("enter number:");
fflush(stdin);
gets(a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]>=0 || a[i]<=9)
{
c++;
}
}
printf("\n %d digit number",c);
getch();
}

File Redirection Input inC

I'm creating a program that takes numbers from a separate .txt file and turns them into a factorial and then finds the amount of times each prime has occurred in the factorial.
I have been working on this code for the last few days and after many hours i keep getting stuck on the same thing, it will compile with no errors but when I try file redirection to get an input from another file it stops and acts like it is asking for input on an endless loop.
Any help would be much appreciated!
#include <stdio.h>
int Storage_array[5];
int current_prime, next_prime, factorial, prime_count, prime_number, num, factorial_current, factorial_next_num, current_number, total_number; //various variables used in program
int find_prime_count(int factorial, int prime_number); //3 functions declared below main()
int find_next_prime(int factorial, int current_prime);
int is_prime(int num);
int a, b, c; //utility varbles
main()
{
if((a=scanf("%d", &c)) == EOF) //checks to see if file is empty
{
return 0;
}
for(b=0; b<c; b++)
{
if((a=scanf("%d", &c)) == EOF) //checks to see if reached end of the file
{
break;
}
scanf("%d", &Storage_array[b]); //paces values from file into the storage array
printf("%d! = ", Storage_array[b]); //formatting the output
for(c=0;c<5;c++)
{
if(c=0) //creating a base case
{
current_prime = 2;
}
else
{
current_prime = next_prime; //updates the current prime after the base case
next_prime = find_next_prime(Storage_array[b], current_prime); //performes the outside functions that fine the next prime number within the factorial
prime_count = find_prime_count(Storage_array[b], current_prime); //performs outside function that finds the number of the current prime within the factorial
printf("(%d^%d)",current_prime ,next_prime); //prints the results in proper format
}
}
printf("\n"); //spaces between factorial numbers
}
}
int is_prime(int num) //function that determines if the input number is a prime number or not
{
for(a=2; a<num; a++) //base case knowing lowest prime is 2
{
if (num % a == 0) //determines if the number is a prime number using remainder when divided by various numbers
{
return a; //returns the number if it is prime
}
}
}
int find_prime_count (int factorial, int prime_number)
{
for(a=0;a<factorial;a++)//tests all possible prime numbers under the input factorial
{
if(a=0) //base case for lowest possible prime in factorial
{
factorial_current = 1;
factorial_next_num = 1;
}
else
{
factorial_current = (a*factorial_next_num);
}
if(factorial_current % prime_number == 0) //determines if the prime number fits into current factorial number
{
current_number = (factorial_current/prime_number); //finds number of times prime number fits in
total_number = (total_number + current_number); //adds total amount of times that prime has fit within the factorial
}
}
return total_number;
}
int find_next_prime (int factorial, int current_prime) //function that determines the next prime within the factorial
{
for(a=current_prime;a<factorial;a++) //checks all possible primes within the factorial
{
if (factorial % current_prime == 0) //determines if the number is a prime number using remainder when divided by various numbers
{
return a; //returns the number if it is next prime
}
}
}
the text file i have has the following content and is called input.txt
7
67
9
43
0

The next palindrome smaller than k using c

The Next Palindrome
A positive integer is called a palindrome if its representation in the decimal system is the same when read from left to right and from right to left. For a given positive integer K, write the value of the smallest palindrome larger than K to output.
Input
The first line contains an integer, which corresponds to K. Assume that K is less than 200000.
Output
Output consists of a single integer, which corresponds to the smallest palindrome larger than K.
Sample Input 1:
808
Sample Output 1:
818
Sample Input 2:
2133
Sample Output 2:
2222.
below is my program, but i am not able to get the output. please tell me where am i going wrong.
#include<stdio.h>
int palindrome(int n)
{
int t,r;
t=n;
while(t!=0)
{
r=r*10;
r=r+(t%10);
t=t/10;
}
if(r==n)
return 1;
else
return 0;
}
int main()
{
int k,d=0,i;
scanf("%d",&k);
for(i=k+1;i<=200;i++){
d=palindrome(i);
if(d==1)
break;
}
printf("%d",i);
return 0;
}
I fixed the indentation, init r with 0 in func palindrome, and fixed the loop that checks for palindromes, it now loop forever (while(1)) until it exists (break) when finding a palindrome.
#include<stdio.h>
int palindrome(int n)
{
int t,r = 0;
t=n;
while(t!=0)
{
r=r*10;
r=r+(t%10);
t=t/10;
}
if(r==n)
return 1;
else
return 0;
}
int main()
{
int k,d=0,i;
scanf("%d",&k);
i = k + 1;
while(1)
{
d=palindrome(i);
//printf("%d ", i);
if(d==1)
break;
i++;
}
printf("%d",i);
return 0;
}

How do I go through a certain number and extract digits smaller than 5 using a recursive function?

it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}

Problem determining if a number is an Armstrong Number

I'm trying to check whether or not the number provided by the user is an armstrong number. Something is wrong though and I can't figure it out.
Any help is appreciated.
Code attached below.
#include<stdio.h>
int fun(int);
int main()
{
int x,a,b,y=0;
printf("enter the number you want to identify is aN ARMSTRONG OR NOT:");
scanf("%d",&a);
for(int i=1 ; i<=3 ; i++)
{
b = a % 10;
x = fun(b);
y = x+y;
a = a/10;
}
if(y==a)
printf("\narmstrong number");
else
printf("\nnot an armstrong number");
return 0;
}
int fun(int x)
{
int a;
a=x*x*x;
return (a);
}
The primary problem is that you don't keep a record of the number you start out with. You divide a by 10 repeatedly (it ends as 0), and then compare 0 with 153. These are not equal.
Your other problem is that you can't look for 4-digit or longer Armstrong numbers, nor for 1-digit ones other than 1. Your function fun() would be better named cube(); in my code below, it is renamed power() because it is generalized to handle N-digit numbers.
I decided that for the range of powers under consideration, there was no need to go with a more complex algorithm for power() - one that divides by two etc. There would be a saving on 6-10 digit numbers, but you couldn't measure it in this context. If compiled with -DDEBUG, it includes diagnostic printing - which was used to reassure me my code was working right. Also note that the answer echoes the input; this is a basic technique for ensuring that you are getting the right behaviour. And I've wrapped the code up into a function to test whether a number is an Armstrong number, which is called iteratively from the main program. This makes it easier to test. I've added checks to the scanf() to head off problems, another important basic programming technique.
I've checked for most of the Armstrong numbers up to 146511208 and it seems correct. The pair 370 and 371 are intriguing.
#include <stdio.h>
#include <stdbool.h>
#ifndef DEBUG
#define DEBUG 0
#endif
static int power(int x, int n)
{
int r = 1;
int c = n;
while (c-- > 0)
r *= x;
if (DEBUG) printf(" %d**%d = %d\n", x, n, r);
return r;
}
static bool isArmstrongNumber(int n)
{
int y = 0;
int a = n;
int p;
for (p = 0; a != 0; a /= 10, p++)
;
if (DEBUG) printf(" n = %d, p = %d\n", n, p);
a = n;
for (int i = 0; i < p; i++)
{
y += power(a % 10, p);
a /= 10;
}
return(y == n);
}
int main(void)
{
while (1)
{
int a;
printf("Enter the number you want to identify as an Armstrong number or not: ");
if (scanf("%d", &a) != 1 || a <= 0)
break;
else if (isArmstrongNumber(a))
printf("%d is an Armstrong number\n", a);
else
printf("%d is not an Armstrong number\n", a);
}
return 0;
}
One problem might be that you're changing a (so it will no longer have the original value). Also it would only match 1, 153, 370, 371, 407. That's a hint to replace the for and test until a is zero and to change the function to raise to the number of digits.
#include<stdio.h>
#include <math.h>
int power(int, int);
int numberofdigits(int);
//Routine to test if input is an armstrong number.
//See: http://en.wikipedia.org/wiki/Narcissistic_number if you don't know
//what that is.
int main()
{
int input;
int digit;
int sumofdigits = 0;
printf("enter the number you want to identify as an Armstrong or not:");
scanf("%d",&input);
int candidate = input;
int digitcount = numberofdigits(input);
for(int i=1 ; i <= digitcount ; i++)
{
digit = candidate % 10;
sumofdigits = sumofdigits + power(digit, digitcount);
candidate = candidate / 10;
}
if(sumofdigits == input)
printf("\n %d is an Armstrong number", input);
else
printf("\n %d is NOT an Armstrong number", input);
return 0;
}
int numberofdigits(int n);
{
return log10(n) + 1;
}
int power(int n, int pow)
{
int result = n;
int i=1;
while (i < pow)
{
result = result * n;
i++;
}
}
What was wrong with the code:
No use of meaningful variable names, making the meaning of the code hard to understand; remember code is written for humans, not compilers.
Don't use confusing code this code: int x,a,b,y=0; is confusing, do all vars get set to 0 or just y. Always put vars that get initialized on a separate line. It makes reading easier. Go the extra mile to be unambiguous, it will pay off big time in the long run.
Use comments: If you don't know what an armstrong number is, than it will be very hard to tell from your code. Put a few meaningful comments in so people know what your code it supposed to do. This will make it easier for you and others because they know what you meant to do and can see what you actually did and solve the difference if need be.
use meaningful routine names WTF does fun(x) do?. Never name anything fun() it's like fact free science, what's the point?
Don't hardcode things, your routine only accepted armstrong3 numbers, but if you can hardcode then why not do return (input == 153) || (input == 370) || ....
Okay so, the thing is that there are also Armstrong numbers that are not just 3 digits for example 1634, 8208 are 4 digit Armstrong numbers, 54748, 92727, 93084 are 5 digit Armstrong numbers and so on. so to check the number is Armstrong or not, here's what I did.
#include <stdio.h>
int main()
{
int a,b,c,i=0,sum=0;
printf("Enter the number to check is an Armstrong number or not :");
scanf("%d",&a);
//checking the digits of the number.
b=a;
while(b!=0)
{
b=b/10;
i++;
}
// i indicates the digits
b=a;
while(a!=0)
{
int pwr = 1;
c= a%10;
//taking mod to get unit place and getting its nth power of their digits
for(int j=0; j<i; j++)
{
pwr = pwr*c;
}
//Adding the nth power of the unit place
sum += pwr;
a = a/10;
//Dividing the number to give the end condition
}
if(sum==b)
{
printf("The number %d is an Armstrong number",b);
}
else
{
printf("The number %d is not an Armstrong number",b);
}
}
/*
Name: Rakesh Kusuma
Email Id: rockykusuma#gmail.com
Title: Program to Display List of Armstrong Numbers in 'C' Language
*/
#include<stdio.h>
#include<math.h>
int main()
{
int temp,rem, val,max,temp1,count;
int num;
val=0;
num=1;
printf("What is the maximum limit of Armstrong Number Required: ");
scanf("%d",&max);
printf("\nSo the list of Armstrong Numbers Before the number %d are: \n",max);
while(num <=max)
{
count = 0;
temp1 = num;
while(temp1!=0)
{
temp1=temp1/10;
count++;
}
if(count<3)
count = 3;
temp = num;
val = 0;
while(temp>0)
{
rem = temp%10;
val = val+pow(rem,count);
temp = temp/10;
}
if(val==num)
{
printf("\n%d", num);
}
num++;
}
return 0;
}
Check No. is Armstrong or Not using C Language
#include<stdio.h>
#include<conio.h>
void main()
{
A:
int n,n1,rem,ans;
clrscr();
printf("\nEnter No. :: ");
scanf("%d",&n);
n1=n;
ans=0;
while(n>0)
{
rem=n%10;
ans=ans+(rem*rem*rem);
n=n/10;
}
if(n1==ans)
{
printf("\n Your Entered No. is Armstrong...");
}
else
{
printf("\n Your Entered No. is not Armstrong...");
}
printf("\n\nPress 0 to Continue...");
if(getch()=='0')
{
goto A;
}
printf("\n\n\tThank You...");
getch();
}
If you are trying to find a armstrong number the solution you posted is missing a case where your digits are great than 3 ...armstrong numbers can be greater than 3 digits (for example 9474). Here is the code in Python, the logic is simple and it can be converted to any other language.
def check_armstrong(number):
num = str(number)
total=0
for n in range(len(num)):
total+=sum(int(num[n]),len(num))
if (number == total):
print("we have armstrong #",total)
def sum(input,power):
input = input**power
return input
check_armstrong(9474)
Here's a way to check whether a number is armstrong or not
t=int(input("nos of test cases"))
while t>0:
num=int(input("enter any number = "))
n=num
sum=0
while n>0:
digit=n%10
sum += digit ** 3
n=n//10
if num==sum:
print("armstronng num")
else:
print("not armstrong")
t-=1
This is the most simplest code i have made and seen ever for Armstrong number detection:
def is_Armstrong(y):
if y == 0:
print('this is 0')
else:
x = str(y)
i = 0
num = 0
while i<len(x):
num += int(x[i])**(len(x))
i += 1
if num == y:
print('{} is an Armstrong number.'.format(num))
break
else:
print('{} is not an Armstrong number.'. format(y))
is_Armstrong(1634)

Resources