For loop skipping numbers in C - c

I am trying to program a prime number checker in c but the following code returns some prime numbers as non prime. I haven't been able to find any non prime which register as prime. I am unsure where I have gone wrong and am beginning to suspect that my for loop is skipping numbers.
#include <stdio.h>
#include <stdlib.h>
int main() {
int nummer = 47203;
printf("Ist %d eine Primzahl?\n", nummer);
int dividey =2;
if (nummer == 2){
printf("nein");
}
for (dividey = 2; dividey <= nummer/2; dividey++){
if (nummer%dividey==0){
printf("nein");
break;
}else {
printf("ja");
break;
}
}
}

Yes, it is skipping numbers - because you've told it to!
If you were checking 15, for example - this is obviously not prime. On the first time through your loop, dividey is set to 2. You then do this check:
if (nummer%dividey==0)
15 % 2 is 1, so this condition fails and you jump to the else part.
Your else part does this:
printf("ja");
break;
I.e. it prints Ja to say it's a prime number and stops looping, even though it's not a prime and you haven't checked all of the divisors. If the loop had continued on to check dividing by 3, it would have realised it's not prime.

Related

Finding Largest Twin Prime

I am trying to create a c program which prompts for user input and then, finds the largest twin prime within that number. This program then loops continuously, prompting the user for an input again and again and finding the largest twin prime until the user enters -1, after which it terminates. I wrote down the basic code, but have yet been able to make it loop continuously when using certain numbers such as 20 and 65. I cannot figure out what is wrong with my code.
I seem to be having another problem as well. For 20, the values show (15,17) instead of (17,19). Obviously the logic is wrong somewhere but I am not sure exactly where either.
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include<conio.h>
int prime(int x)
{
int i,numroot;
numroot=sqrt(x);
for(i=2;i<=numroot;i++)
if(x%i==0){
return(0);
}
return(1);
}
int main()
{
double N;
printf("This program prints out all the possible twin primes until a specific number which...\nyou can choose!");
printf("\nA note of caution: Although this program accepts decimals, the value entered must be between 5 and 10^9,inclusive of the 2 numbers.");
printf("\nKey in -1 to exit.");
printf("\nEnter N value upto which twin primes ought to be calculated until: ");
scanf("%lf",&N);
while (N!=-1) {
if (N<5 || N>pow(10,9)) {
printf("\nNumber not in the valid range was inputted. \nPlease reenter the value: ");
scanf("%lf",&N);
}
else {
int n;
n=floor(N);
int prime(int x);
int f,originalval;
originalval=N;
f=prime(n);
while(f==0){//Calculates for largest prime number below user input
n--;
f=prime(n);
}
int smallint=n-2;
while(prime(smallint)==1){
n--;
f=prime(n);
while(f==0){
n--;
f=prime(n);
}
int smallint=n-2;
}
printf("The largest twin prime pair not above %d is (%d,%d)",originalval,smallint,n);
printf("\nPlease re-enter the value:");
scanf("%lf",&N);
}
}
printf("\nProgram successfully terminated.");
return 0;
}
You are doing a research about prime numbers "upto" a given number N.
In this class of problems is more efficient (although more expensive in RAM space) to store information in tables of primes and composite numbers, like the Sieve of Eratosthenes.
Once you have filled the table with the information of which numbers are prime and composite, it's just a matter of iterate on the table to look for the twin primes, wherever they are.
However, although you inform to the user that all the twin primes will be shown, actually what your program does is trying to show only the lastest.
Please, have clear which is the goal of your program.
On the other hand, you are redefining the identifier smallint inside the innest loop, which is, for sure, a logical error.
In case you cannot use arrays to store the Sieve of Eratosthenes, then I show you here a method that is not hard to implement (but it's not, of course, the most efficient; however it will avoid a lot of redundant computations).
The twin primes (greater than 4) can be of two different forms:
6k-1, 6k+1
6k+1, 6k+5
So, I would jump in the sequence of numbers having the form 6k+1, 6k+5, for k = 0, 1, 2, 3, ..., so that I only would analyze the odd numbers in the sequence:
5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, 41, 43, 47, 49, ...
This can be obtained by adding 2, then 4, then 2, then 4, then 2, then 4...
So, one can take the first pair, let's say 5 and 7.
We divide both of them by the odd numbers of the form 6k+1 and 6k+5 less than the square root of the greatest of them (sqrt(7)).
If the less number (in this case 5) would be divisible by some number, we pick the following number in the list, which is 11, and divide it by all the numbers that were used so far to test if 7 is prime or not. From this point, we follow by dividing together, 7 and 11, by the remaining numbers up to sqrt(11), and so on.
Note that, for big numbers, 6k+1 and 6k+5 have very similar square roots.
If the opposite case happens, that is, that for the pair (5, 7), the biggest element of the couple (in this case: 7) is divisible by some other number, then we discard both of them (5 and 7) and pick the following two elementos of the list (in this example would be 11 and 13). So, we start the search from scratch (that is, by dividing by small numbers).
finally, if the loop ends without finding divisors for any element of the couple (which is indeed the case for 6 and 7), then we can inform that this couple is of twin primes.
(Or well we can keep silent).
Then, we discard the smallest element (in this case: 5) and retain the biggest element (in this case: 7).
Since we already know that 7 is prime, we only pick the following element of the list above (in this case, 11), and search for divisors of it, only.
I think that the method I have explained will avoid to you a lot of redundant computations.
Besides, it's necessary to keep the latest updated couple of twin primes found. I assume that is not necessary that I explain to you how to do that.
We should procure that both of numbers are prime. Between difference is 2. As you know first twin prime is (3,5). I haven't found a formula what I expected. So, I've used iteration for solution. If you look through the code, you can understand.
#include <stdio.h>
#include <math.h>
int twinPrime(int m);
int IsPrime(unsigned int number);
int main()
{
double N;
int floored;
int prime;
printf("This program prints out all the possible twin primes"
"until a specific number which...\nyou can choose!");
printf("\nA note of caution: Although this program accepts decimals, "
"the value entered must be between 5 and 10^9,inclusive of the 2 numbers.");
printf("\nKey in -1 to exit.");
printf("\nEnter N value upto which twin primes ought to be calculated until: ");
scanf("%lf",&N);
while (N != -1)
{
if (N < 5 || N > pow(10,9))
{
printf("\nNumber not in the valid range was inputted. \n"
"Please reenter the value: ");
scanf("%lf",&N);
}
else
{
floored = floor(N);
prime = twinPrime(floored);
printf("The largest twin prime pair not above %d is (%d,%d)",floored,prime - 2,prime);
printf("\nPlease re-enter the value:");
scanf("%lf",&N);
}
}
printf("\nProgram successfully terminated.");
return 0;
}
int twinPrime(int m)
{
int p = 3;
int q = 5;
for (; q < m - 1; q += 2)
{
if (IsPrime(q))
{
if (q - p == 2)
{
continue;
}
p = q;
}
}
return q;
}
int IsPrime(unsigned int number)
{
if (number <= 1) return 0; // zero and one are not prime
if ((number > 2) && ((number % 2) == 0)) return 0; //no even number is prime number (bar 2)
unsigned int i;
for (i=2; i*i<=number; i++)
{
if (number % i == 0) return 0;
}
return 1;
}

spoj.com prime generator time limit exceeded

Getting time limit exceeded on submitting answer. I am also facing same problem with 2-3 more questions that I have submitted on spoj.com.
http://www.spoj.com/problems/PRIME1/
Peter wants to generate some prime numbers for his cryptosystem. Help him! Your task is to generate all prime numbers between two given numbers!
Input
The input begins with the number t of test cases in a single line (t<=10). In each of the next t lines there are two numbers m and n (1 <= m <= n <= 1000000000, n-m<=100000) separated by a space.
Output
For every test case print all prime numbers p such that m <= p <= n, one number per line, test cases separated by an empty line.
Example
Input:
2
1 10
3 5
Output:
2
3
5
7
3
5
Warning: large Input/Output data, be careful with certain languages (though most should be OK if the algorithm is well designed)
Here is my code in C.
#include <stdio.h>
int main()
{
int t,i,k,count;
long long int j=0,m=0,n=0;
scanf("%d",&t);
for(i=1;i<=t;i++)
{
scanf("%lld%lld",&m,&n);
for(j=m;j<=n;j++)
{
count=0;
for(k=1;k<=j/2;k++)
{
if(j%k==0)
count++;
if(count>1)
break;
}
if(count==1)
printf("%lld\n",j);
}
printf("\n");
}
return 0;
}
Your algorithm is O((m-n)*n) which of course won't run within the allocated time limit. Let's go over your code:
count=0;
for(k=1;k<=j/2;k++)
{
if(j%k==0)
count++;
if(count>1)
break;
}
if(count==1)
printf("%lld\n",j);
Micro optimization: Why do you need a counter? You could get away with a bool.
Optimization: Why are you testing primes j/2? If j has a divisor greater than 1 than it's guaranteed that j has a divisor that's at most sqrt(j).
Micro Optimization: Don't consider even numbers at all, except for 2.
bool prime = j==2 || j%2==1 ;
for(k=2;prime && k*k<=j;k++)
{
if(j%k==0) prime = false;
}
}
if(prime) printf("%lld\n",j);
Now this is O((m-n)*sqrt(n)) which is a lot faster.
I suppose this won't make the limit. You could extend the second micro-optimization to skip numbers divisible by 3 very easy.
Optimization: If this is still not enough then you have to do a pseudo-primality test. One test that's very easy to implement in O(log(n)) is https://en.wikipedia.org/wiki/Fermat_primality_test. With this the complexity is down to O((m-n)*log(n)) which should be run in the available time limit.

C prime factorization (loop failure?)

I've been looking into this simple piece of code for 1.5 hrs now and do not find the mistake. I start going crazy ;)
Could anyone of you with a fresh mind and view give me a little hint, where I might have the mistake in? (I am relatively new to C)
The problem is: The code works fine for most of the numbers I entered and tested, but accidentically I found a number that does not work: 3486118 (or 55777888 which is a multiple of it) It goes right for the first loop(s), but after factor 2 it becomes an endless loop.
Here is my code: (any help is greatly appreciated)
// Program calculates prime factors of entered number and returns them
#include <stdio.h>
int main() {
long int num, num_cp;
long int product=1;
/*prime number array up to 100.000*/
long int prime[] = {2, 3, **[...cut out MANY numbers...]** 99971, 99989, 99991};
printf("Please enter a positive integer:\n");
scanf("%li", &num);//55777888 or 3486118 not working... why?
//copy the entered number to keep the original for comparison with "product" and "break;" if equal
num_cp=num;
printf("prime factorization of %li:\n\n", num);
for (int i=0; i<sizeof(prime); i++) {
if (num_cp%prime[i]==0) {
num_cp/=prime[i];
product*=prime[i];
if (product==num) {
printf("%li\n\n", prime[i]);
break;
}
printf("%li*", prime[i]);
//If prime factor found but "product" is still not equal to "num" reset loop counter "i" to -1 (==0 in next loop)
i=-1;
}
}
printf("END");
return 0;
}
"I've been looking into this simple piece of code for 1.5 hrs now and do not find the mistake. I start going crazy ;)"
Don't. Leave it. Go away and eat a pizza. Veg out in front of your favourite movie. Have a shower. Aim for a new high-score on 2048 (or whatever). Your brain gets stuck in a rut and you are no longer seeing your code. You are only seeing what you think your code is.
When you get your brain out of the rut, then -- and only then -- go back and actually read the code you wrote. Not the code you think you wrote, but the code you actually wrote. Yes, they are different.
The prime factors of 55777888 are 2·2·2·2·2·1743059, where the last factor is too large to be contained in your list.
You can fix this in your code: When the product is equal to the product of the prime factors you have found, num_cp is 1. If num_cp is greater than one after you have exhausted your prime list, it is a factor of num. If num/num_cp is smaller than the largest prime you have checked, you can assume that the remaining value of num_cp is a prime. If it wasn't you'd have found more factors earlier.
You can fix this by adding an additional check after your main loop:
if (num_cp > 1) printf("%li\n\n", num_cp);
(If long int is a 64-bit number on your system, you're still not safe: The remaining factor might be made up of several numbers that are not in your array.)
Finally: Resetting the for loop counter so that the loop starts over isn't a good idea. It always starts from the beginning and re-checks primes that you have already checked. And it just isn't natural program flow, which makes it hard to read. A while loop instead of the inner if block would be more natural in my opinion.
Edit: To illustrate:
#include <stdio.h>
int main() {
long int num;
/* prime number array up to 100.000 */
long int prime[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31};
int nprime = sizeof(prime) / sizeof(*prime);
num = 55;
printf("%li == ", num);
for (int i = 0; i < nprime; i++) {
long int p = prime[i];
if (num <= 1) break;
while (num % p == 0) {
num /= prime[i];
printf("%li", p);
if (num > 1) printf(" * ");
}
}
if (num > 1) printf("%li", num);
printf("\n");
return 0;
}
Things to note:
Instead of resetting the main loop counter i, a while loop is used, which consumes all repetitions of the same factor. If a prime p doesn't divide the number, the while loop isn't entered, just like an if clause.
I've removed the copy of num and used num throughout, mainly to remove clutter. I've also removed the product. Your logic that all prime factors should multiply to the original number, is good. But it also works the other way round: After dividing the number by all primes, we are left with 1. And we have to divide the number anyways. By removing the product, we have to keep track of only one variable instead of two.
I've moved the break condition to the front, so we catch negative numbers and 0 early.
That said, your way to code isn't wrong, just maybe a bit unusual in places.

figure out the prime numbers between 0 and 1000?

I'm trying to make a programm that can calculate the prime numbers between 0 and 1000, the compiler says it has no warning and no erros too, but when i run the programm it gives me an execution error, i have no ideia what it is, does anybody could take a look at my code??
NOTE: i'm a beginner in programming.
#include <stdio.h>
#include <stdlib.h>
int main(){
int i=0;
for (i=0;i<1000;i++){
if (i % 1 == 0 && i % i == 0){
printf("%d",i );
}
printf(" ");
}
return 0;
}
You are performing a division by zero in
i % i == 0
for i = 0.
Moreover, even if you start you cycle from i = 1, the code will give you every integer between 1 and 999, for the expression
i % 1 == 0 && i % i == 0
is true whenever i != 0. Here is a fixed algorithm (not the most efficient, admittedly):
#include <stdio.h>
int main(){
int i; /* no need to initialize to zero */
int j; /* we need a second counter */
for (i=2;i<1000;i++){ /* start from 2 -- one is not prime */
for (j=2;j<i;j++){ /* check for nontrivial divisors */
if (i % j == 0) {
break; /* nontrivial divisor found -> not a prime */
}
}
if (j == i) { /* this means the cycle above run till end */
printf("%d ",i ); /* hence no nontrivial divisors, hence a prime */
}
}
printf("\n");
return 0;
}
The problem is with the expression i % i. In the first iteration of your loop, i is 0, so you are dividing by zero.
You should iterate from 1 to 1000, because dividing with 0 is not allowed and it gives floating point exception.
Also, your algorithm is not correct.
Use code from here:
http://www.programmingsimplified.com/c/source-code/c-program-for-prime-number
What happens when i is 0? My guess is you want to start your loop at 1 (as well as fix your prime number check).
Below python code may help you for following purposes:
To figure out the total number of primes in the range of 0 to given number (upper limit)
To know about each and every number whether that is prime or not
The Complete list of primes fall in the specified range
primes=[]
limit = int(input('What is the maximum limit?'))
for n in range(2,limit+1):
for x in range(2,n):
if n%x == 0:
print('{} -> Not prime'.format(n))
break
else:
primes.append(n)
print('{} -> Prime'.format(n))
print(primes)
print('Total {} primes found'.format(len(primes)))
If you don't want non-prime numbers to display then you can comment out #print('{} -> Not prime'.format(n)) this line and if you don't even want to know all primes comment the consecutive print statement as well i.e. #print('{} -> Prime'.format(n))

Perfect square in fibonacci sequence?

Create a program to find out the first perfect square greater than 1 that occurs in the Fibonacci sequence and display it to the console.
I have no output when I enter an input.
#include <stdio.h>
#include <math.h>
int PerfectSquare(int n);
int Fibonacci(int n);
main()
{
int i;
int number=0;
int fibNumber=0;
int psNumber=0;
printf("Enter fibonacci number:");
scanf("%i",&number);
fibNumber = Fibonacci(number);
psNumber = PerfectSquare(fibNumber);
if(psNumber != 0){
printf("%i\n",psNumber);
}
}
int PerfectSquare(int n)
{
float root = sqrt(n);
if (n == ((int) root)*((int) root))
return root;
else
return 0;
}
int Fibonacci(int n){
if (n==0) return 0;
if (n==1) return 1;
return( Fibonacci(n-1)+Fibonacci(n-2) );
}
Luke is right. If your input is n, then the Fibonacci(n) returns the (n+1)th Fibonacci number.
Your program check whether (number +1)th is perfect square or not actually.
If you enter 12, then there is output. Because the 13th Fibonacci number is 144. And it is perfect square. PS: print fibNumber instead of psNumber.
printf("%i\n", fibNumber);
Right now you're only calculating one Fibonacci number and then testing whether it's a perfect square. To do this correctly you'll have to use a loop.
First suggestion is to get rid of the recursion to create fib numbers. You can use 2 variables and continually track the last 2 fib numbers. They get added something like:
fib1=0;fib2=1;
for(i=3;i<MAXTOCHECK;i++)
{
if(fib1<fib2)
fib1+=fib2;
else
fib2+=fib1;
}
What is nice about this method is that first you can change you seeds to anything you want. This is nice to find fib like sequences. For example Lucas numbers are seeded with 2 and 1. Second, you can put your check for square inline and not completely recalculate the sequence each time.
NOTE: As previously mentioned, your index may be off. There is some arbitrariness of indexing fib numbers from how it is initially seeded. This can seen if you reseed with 1 and 1. You get the same sequence shifted by 1 index. So be sure that you use a consistent definition for indexing the sequence.

Resources