Finding biggest prime number in user-inputted number - C - c

I have a problem with my code. The topic is to write a C program which finds biggest prime number in the number inputted by user.
Ex.:
Enter number: 46656665326
Output: 66566653
This is my code:
#include <stdio.h>
#include <stdlib.h>
int is_prime(unsigned long long a)
{
if(a<=1)
return 0;
if(a==2)
return 1;
for(unsigned long long p=2; p<a; p++)
if(a%p==0)
return 0;
return 1;
}
unsigned long long find_largest_prime_number(unsigned long long number)
{
unsigned long long prime=0;
int count=0;
unsigned long long count2=1;
unsigned long long pom=0;
unsigned long long pom3=0;
pom3=number;
while(pom3!=0)
{
count++;
pom3/=10;
}
count++;
int pom_1=0;
while(pom_1<count)
{
count2*=10;
pom_1++;
}
pom=number;
while(count2>=10)
{
unsigned long long pom2=pom;
while(pom2!=0)
{
if(is_prime(pom2))
if(pom2>prime)
prime=pom2;
pom2/=10;
}
count2/=10;
pom=pom%count2;
}
return prime;
}
int main()
{
unsigned long long x=0;
printf("Enter number: ");
int n1=scanf("%llu", &x);
if(n1!=1)
{
printf("incorrect input");
return 1;
}
printf("%llu", find_largest_prime_number(x));
return 0;
}
The problem is it works with max 13-digit number but it freezes when the input number has more than 13 digits.
Ex. it freezes when I enter: 215911504934497
Please help, what's wrong with the code?

The reason for block boils down to this:
int is_prime(unsigned long long a)
{
...
for(unsigned long long p=2; p<a; p++)
if(a%p==0)
return 0;
return 1;
}
If you enter 215911504934497 then the find_largest_prime_number will call is_prime(215911504934497). 215911504934497 is a big number, and doing a%p for each p from 2 to 215911504934497 is cpu expensive (I think at least you could p < a/2). Your program get's stuck in this loop. You can observe that by doing a simple printf inside it:
int is_prime(unsigned long long a)
{
...
for(unsigned long long p=2; p<a; p++) {
printf("%lld %lld\n", p, a);
if(a%p==0)
return 0;
}
return 1;
}

Your code is perfectly correct. It is simply terribly inefficient and therefore takes very, very long time just to find out if a single large number is prime.
Here is better version of is_prime:
It tests divisors only up to the square root of the number to be tested.
It only tests odd divisors, if the number is not divisible by two, it's pointless to test if it's divisible by 4, 6, 8 etc.
// long long integer square root found somewhere on the internet
unsigned long long isqrt(unsigned long long x)
{
unsigned long long op, res, one;
op = x;
res = 0;
/* "one" starts at the highest power of four <= than the argument. */
one = 1LL << 62; /* second-to-top bit set */
while (one > op) one >>= 2;
while (one != 0) {
if (op >= res + one) {
op -= res + one;
res += one << 1; // <-- faster than 2 * one
}
res >>= 1;
one >>= 2;
}
return res;
}
int is_prime(unsigned long long a)
{
if (a <= 1 || a == 2 || a % 2 == 0)
return 0;
unsigned long long count = 0;
unsigned long long limit = isqrt(a) + 1;
for (unsigned long long p = 3; p < limit; p += 2)
{
if (a % p == 0)
return 0;
}
return 1;
}
Further optimisations are of course possible. E.g. it is also pointless to test for multiples of 3 if the number was not divisible by 3 etc. Also if you want to find a range of prime numbers there are probably other approaches to be taken into account.

Focusing on square root finally solved the issue.
is_prime should be looking like that:
int is_prime(unsigned long long a)
{
int i=0;
int count=0;
int test=0;
int limit=sqrt(a)+1;
if(a<=1)
return 0;
if(a==2)
return 1;
if(a%2==0)
test=1;
else
for(i=3; i<limit && !test; i+=2, count++)
if(a%i==0)
test=1;
if(!test)
return 1;
else
return 0;
}

As mentioned by other contributors, and in the comments, your code is "crashing" simply because it is inefficient.
Many of the other contributors have used a more efficient way of checking whether a number is prime by checking that number against its divisors.
HOWEVER, this is not the most efficient manner to go about doing it, especially if you are whether multiple numbers are prime.
In order to make it even faster, I suggest an implementation of the Sieve of Eratosthenes:
#define MAX_N 4294967296 //idk how big of an array your computer can actually handle. I'm using 2^32 here.
//Declare as a global variable for extra memory allocation
//unsigned char is used as it is only 1 byte (smallest possible memory alloc)
//0 for FALSE, 1 for TRUE.
unsigned char is_prime[MAX_N+1];
//Populate the is_prime function up to your input number (or MAX_N, whichever is smaller)
//This is done in O(N) time, where N is your number.
void performSieve(unsigned long long number){
unsigned long long i,j;
unsigned long long n = (number>MAX_N)?MAX_N:number; //quick way (ternary operator): "whichever is smaller"
//Populating array with default as prime
for(i=2; i<=n; i++) is_prime[i] = 1;
for(i=4; i<=n; i+=2) is_prime[i] = 0; //all even numbers except 4 is not prime
for(i=3; i<=n; i+=2){
if(is_prime[i] == 1)
for(j=i*i;j<=n;j+=i){ //all the multiples of i except i itself are NOT prime
is_prime[i] == 0;
}
}
}
//isPrime function
unsigned char isPrime(unsigned long long n){
if(n<=1) return 0; //edge cases
//Check if we can find the prime number in our gigantic sieve
if(n<=MAX_N){
return is_prime[n]; //this is O(1) time (constant time, VERY FAST!)
}
//Otherwise, we now use the standard "check all the divisors" method
//with all the optimisations as suggested by previous users:
if(n%2==0) return 0; //even number
//This is from user #Jabberwocky
unsigned long long limit = isqrt(a);
for (unsigned long long p = 3; p <= limit; p += 2) {
if (a % p == 0) return 0;
}
return 1;
}

Related

Right implementation of two functions related to fibonacci and prime numbers

I have a very long question and some part of the question, involves two functions named gp(a,t) and fibo(a,t).
gp(a,t) gets two integer numbers a ,t and must return the smallest prime number that is greater than or equal to (t/100)*a
fibo(a,t) gets two integer numbers a,t and must return the biggest member of fibonacci series that is less than or equal to (t/100)*a. (We consider 0 as the first member of fibonacci series in this problem, so it is 0 1 1 2 3 5 8 13 ...)
(The problem didn't mention that we must save that (t/100)*a as float but according to its examples, it must be considered a float for example if it is 3.5 then gp must return 5 and not 3.)
I implemented this functions but in some unknown test cases, it fails and so I want to know which part of my functions are wrong. Is there any a,t that my functions give wrong answer for them?
Note: I defined everything as long long because the main very long part of the question said to use long long because the numbers will get big.
Note 2: It doesn't give time limit error, so there is no problems like infinite loop or not optimised calculation of prime numbers.
My functions: (written in c)
long long int primeCheck(long long int a)
{
if (a==1 || a ==0)
{
return 0;
}
long long int isPrime = 1;
;
for (long long int i =2;i*i<=a;i++)
{
if (a%i==0)
{
isPrime=0;
break;
}
}
return isPrime;
}
long long int fibo (long long int a, long long int t)
{
float check = (t*1.00/100)*1.00*a;
if (check ==0)
{
return 0;
}
else if (check==1)
{
return 1;
}
long long int f_n_2 = 0;
long long int f_n_1 = 1;
long long int f_n=0;
while (f_n<=check)
{
f_n = f_n_2 + f_n_1;
f_n_2 = f_n_1;
f_n_1 = f_n;
if (f_n > check)
{
return f_n_2;
}
else if (f_n == check)
{
return f_n;
}
}
return 0;
}
long long int gp (long long int a , long long int t)
{
float check = (t*1.00/100)*1.00*a;
long long int i=ceil(check);
while(1)
{
if (primeCheck(i) )
{
return i;
}
i++;
}
return 0;
}
PS1. The problem is Solved. The issue was in the judge system and the code is just fine!

SPOJ COINS DP and Recursive Approach

I have recently started solving DP problem and I came across COINS. I tried to solve it using DP with memoization and it works fine if I use int array(I guess).
Here is my approach(few modifications left):
#include <stdio.h>
#include <stdlib.h>
int dp[100000];
long long max(long x, long y)
{
if (x > y)
return x;
else
return y;
}
int main()
{
int n,i;
scanf("%d",&n);
dp[0]=0;
for(i=1;i<=n;i++)
{
dp[i]=max(i,dp[i/2] + dp[i/3] + dp[i/4]);
}
printf("%d\n",dp[n]);
return 0;
}
But I don't understand as soon as I use long long array I get SIGSEGV.
I searched and there seems to be a recursive solution that I am not understanding.
Can someone help me out here?
The limits say n<=10e9, array size of which will always result in memory overflow and hence, SIGSEGV. It does not matter what is the type of your dp-array.
There are yet other errors in your code. Firstly, there are test-cases, which you have to read till EOF. Secondly, since the limits are 10e9, you are looping n times !! Surely TLE.
Now, for the recursive solution, using memoization:
Firstly, save the answer values till 10e6 in the array. Will help save time. It can be done as:
long long dp[1000000] = {0};
for(int i = 1; i < 1000000; i++){
dp[i] = max(i, dp[i/2] + dp[i/3] + dp[i/4]);
}
Now, for any input n, find the solution as,
ans = coins(n);
Implement coins function as:
long long coins(long long n){
if (n < 1000000)
return dp[n];
return coins(n/2) + coins(n/3) + coins(n/4);
}
Why this recursive solution works:
It is very obvious that answer for all n >= 12 will be ans[n/2] + ans[n/3] + ans[n/4], so for n > 10e6, that is returned.
The base condition for the recursion is just to save time. You can also return it for 0, but then then you will have to take care of corner cases. (You get my point there)
Exact code:
#include<stdio.h>
long long dp[1000000] = {0};
long long max(long long a, long long b){
return a>b?a:b;
}
long long coins(long long n){
if (n < 1000000)
return dp[n];
return coins(n/2) + coins(n/3) + coins(n/4);
}
int main(){
for(long long i = 1; i < 1000000; i++){
dp[i] = max(i, dp[i/2] + dp[i/3] + dp[i/4]);
}
long long n;
while(scanf("%lld",&n) != EOF){
printf("%lld\n", coins(n));
}
return 0;
}

find all Carmichael numbers in a given interval [a,b) - C

I am working in a math software with different features one of them to be to find all Carmichael numbers in a given interval [a,b)
This is my code, but I don't know if I have done it correctly or not cause I can't test it since the smallest Carmichael number is 560 which is too big for my pc to process.
#include <stdio.h>
int main() {
unsigned int begin, end;
printf("Write an int (begin):\n");
scanf("%d", &begin);
printf("Write an int (end):\n");
scanf("%d", &end);
int i;
for( int i=begin; i<end; i++ ) {
long unsigned int a_nr = i-1;
int a[a_nr];
for( int j=0; j<a_nr; j++ ) {
a[j] = j;
}
unsigned long c_nr[a_nr];
for( int k=0; k<a_nr; k++ ) {
unsigned long current_c_nr;
int mod;
for( int l=0; l<i; l++ ) {
current_c_nr= current_c_nr * a[k];
}
mod = current_c_nr%i;
if( mod==a[k] && mod!=a[k] ) {
c_nr[k] = i;
}
}
}
return 0;
}
If it is not correct, where is the mistake?
Thank you
P.S Overflow should be prevented.
When you say "This is my code, but I don't know if I have done it correctly or not cause I can't test it since the smallest Carmichael number is 560 which is too big for my pc to process" then the conclusion is -- you haven't done it correctly. You should be able to process 561 (560 must be a typo) in a small fraction of a second. Even if your algorithm is in principle correct, if it can't handle the smallest Carmichael number then it is useless.
n is Carmichael if and only if it is composite and, for all a with 1 < a < n which are relatively prime to n, the congruence a^(n-1) = 1 (mod n) holds. To use this definition directly, you need:
1) An efficient way to test if a and n are relatively prime
2) An efficient way to compute a^(n-1) (mod n)
For the first -- use the Euclidean algorithm for greatest common divisors. It is most efficiently computed in a loop, but can also be defined via the simple recurrence gcd(a,b) = gcd(b,a%b) with basis gcd(a,0) = a. In C this is just:
unsigned int gcd(unsigned int a, unsigned int b){
return b == 0? a : gcd(b, a%b);
}
For the second point -- almost the worst possible thing you can do when computing a^k (mod n) is to first compute a^k via repeated multiplication and to then mod the result by n. Instead -- use exponentiation by squaring, taking the remainder (mod n) at intermediate stages. It is a divide-and-conquer algorithm based on the observation that e.g. a^10 = (a^5)^2 and a^11 = (a^5)^2 * a. A simple C implementation is:
unsigned int modexp(unsigned int a, unsigned int p, unsigned int n){
unsigned long long b;
switch(p){
case 0:
return 1;
case 1:
return a%n;
default:
b = modexp(a,p/2,n);
b = (b*b) % n;
if(p%2 == 1) b = (b*a) % n;
return b;
}
}
Note the use of unsigned long long to guard against overflow in the calculation of b*b.
To test if n is Carmichael, you might as well first test if n is even and return 0 in that case. Otherwise, step through numbers, a, in the range 2 to n-1. First check if gcd(a,n) == 1 Note that if n is composite then you must have at least one a before you reach the square root of n with gcd(a,n) > 1). Keep a Boolean flag which keeps track of whether or not such an a has been encountered and if you exceed the square root without finding such an a, return 0. For those a with gcd(a,n) == 1, compute the modular exponentiation a^(n-1) (mod n). If this is ever different from 1, return 0. If your loop finishes checking all a below n without returning 0, then the number is Carmichael, so return 1. An implementation is:
int is_carmichael(unsigned int n){
int a,s;
int factor_found = 0;
if (n%2 == 0) return 0;
//else:
s = sqrt(n);
a = 2;
while(a < n){
if(a > s && !factor_found){
return 0;
}
if(gcd(a,n) > 1){
factor_found = 1;
}
else{
if(modexp(a,n-1,n) != 1){
return 0;
}
}
a++;
}
return 1; //anything that survives to here is a carmichael
}
A simple driver program:
int main(void){
unsigned int n;
for(n = 2; n < 100000; n ++){
if(is_carmichael(n)) printf("%u\n",n);
}
return 0;
}
output:
C:\Programs>gcc carmichael.c
C:\Programs>a
561
1105
1729
2465
2821
6601
8911
10585
15841
29341
41041
46657
52633
62745
63973
75361
This only takes about 2 seconds to run and matches the initial part of this list.
This is probably a somewhat practical method for checking if numbers up to a million or so are Carmichael numbers. For larger numbers, you should probably get yourself a good factoring algorithm and use Korseldt's criterion as described in the Wikipedia entry on Carmichael numbers.

error with array size

I am trying to make a program that calculates the amount of prime numbers that don't exceed an integer using the sieve of Eratosthenes. While my program works fine (and fast) for small numbers, after a certain number (46337) I get a "command terminated by signal 11" error, which I suppose has to do with array size. I tried to use malloc() but I didn't get it quite right. What shall I do for big numbers (up to 5billion)?
#include <stdio.h>
#include<stdlib.h>
int main(){
signed long int x,i, j, prime = 0;
scanf("%ld", &x);
int num[x];
for(i=2; i<=x;i++){
num[i]=1;
}
for(i=2; i<=x;i++){
if(num[i] == 1){
for(j=i*i; j<=x; j = j + i){
num[j] = 0;
}
//printf("num[%d]\n", i);
prime++;
}
}
printf("%ld", prime);
return 0;
}
Your array
int num[x];
is on the stack, where only small arrays can be accommodated. For large array size you'll have to allocate memory. You can save on memory bloat by using char type, because you only need a status.
char *num = malloc(x+1); // allow for indexing by [x]
if(num == NULL) {
// deal with allocation error
}
//... the sieve code
free(num);
I suggest also, you must check that i*i does not break the int limit by using
if(num[i] == 1){
if (x / i >= i){ // make sure i*i won't break
for(j=i*i; j<=x; j = j + i){
num[j] = 0;
}
}
}
Lastly, you want to go to 5 billion, which is outside the range of uint32_t (which unsigned long int is on my system) at 4.2 billion. If that will satisfy you, change the int definitions to unsigned, watching out that your loop controls don't wrap, that is, use unsigned x = UINT_MAX - 1;
If you don't have 5Gb memory available, use bit status as suggest by #BoPersson.
The following code checks for errors, tested with values up to 5000000000, properly outputs the final count of number of primes, uses malloc so as to avoid overrunning the available stack space.
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned long int x,i, j;
unsigned prime = 0;
scanf("%lu", &x);
char *num = malloc( x);
if( NULL == num)
{
perror( "malloc failed");
exit(EXIT_FAILURE);
}
for(i=0; i<x;i++)
{
num[i]=1;
}
for(i=2; i<x;i++)
{
if(num[i] == 1)
{
for(j=i*i; j<x; j = j + i)
{
num[j] = 0;
}
//printf("num[%lu]\n", i);
prime++;
}
}
printf("%u\n", prime);
return 0;
}

How to check whether a no is factorial or not?

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 ??
* */
}

Resources