Below is a C code that generates 1000 random positive integers, for each number we check primality, palindromic property, and the square root of the sum of the digits. The purpose is to find/discover positive integers with interesting/beautiful property such as:
"12345678910987654321 is a prime number"
or
"12321 is a palindromic number and the sum of its digits is a square number." (although this may not be that interesting)
Is there a better and efficient way to write the code? especially if I want it to include large integers.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
int is_prime(unsigned long int n){
unsigned int p;
if (n == 2){
return 1;
}
if (!(n & 1) || n < 2 ) {
return 0;
}
for (p = 3; p <= n/p; p += 2){
if (!(n % p)){
return 0;}
}
return 1;
}
int palindrome(unsigned long int n){
char strnum[20];
int i, nstr;
float cond;
sprintf(strnum, "%ld", n);
nstr = strlen(strnum);
cond = (nstr-1)/2.0;
for (i=0; i< cond; i++){
if (strnum[i] != strnum[nstr-1-i]){
return 0;
}
}
return 1;
}
int sum_of_digits(unsigned long int n){
char strnum[20];
int i, nstr, term, total = 0;
sprintf(strnum, "%ld", n);
nstr = strlen(strnum);
for (i=0; i<nstr; i++){
term = ((int)(strnum[i])) - 48;
total = total + term;
}
return total;
}
int main(){
unsigned long int i;
float added_digits;
unsigned int prime_status, palindrome_status;
int N = 1000;
srand(4);
for (int j=0; j < N; j++){
i = rand();
printf("Number = %ld\n", i);
prime_status = is_prime(i);
switch (prime_status){
case 1:
printf("Prime number status: True\n");
break;
default:
printf("Prime number status: False\n");
}
palindrome_status = palindrome(i);
if (palindrome_status==1){
printf("The number is a Palindrome\n");
}
else{
printf("The number is not a Palindrome\n");
}
added_digits = sqrt(sum_of_digits(i));
printf("(Square root) sum of digits: %f\n\n", added_digits);
}
}