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;
}
Related
I am doing this problem:
"We have a huge decimal number N. Write a program to determine the followings:
The number of digits in N.
Is N an even number?
The number of zeros in it.
Is N a multiple of 11? Note that we can determine if N is a multiple of 11 by checking the difference between the sum of the odd positioned digits and the sum of the even positioned digits. For example, 82375 is not a multiple of 11 because the sum of the even positioned digits is 2 + 7 = 9, and the sum of the odd positioned digits is 8 + 3 + 5 = 16, and the difference between 9 and 16 is 7, which is not a multiple of 11.
We will give you the number one digit per line. For example, if you get digits ‘1’, ‘2’, ‘3’, ’4’, ‘0’ in order, then the number is 12340. The number will not start with 0.
Input Format
The input has several lines. Each line has a digit. EOF indicates the end of input.
Output Format
Output the four answers above line by line. If the number is even output a 1; otherwise a 0. If the number is a multiple of 11 output a 1; otherwise output a 0.
Subtask
10 points: you can store the decimal number in an integer without overflow
10 points: the number of digits is no more than 32768, so you can store digits in an array
80 points: you will get MLE if you use array"
my code is:
#include <stdio.h>
#include <stdbool.h>
int digit(long n);
int is_even(int n);
int count_zeros(long n);
int is_multiple(long n);
int main() {
int digits = 0;
long x;
scanf("%ld", &x);
digit(x);
int even = is_even(x);
printf("%d\n", even);
printf("%ld\n",count_zeros(x));
printf("%ld\n", is_multiple(x));
}
int digit(long n)
{
int digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
printf("%ld\n", digits);
}
int is_even(int n)
{
if (n % 2 == 0)
return true;
else
return false;
}
int count_zeros(long n)
{
int count = 0;
while (n > 0) {
n /= 10;
if (n %10 == 0)
count++;
}
return count;
}
int is_multiple(long n)
{
if (n % 11 == 0) {
return true;
}
else
return false;
}
Basically i dont know how to meet the problem's requirement, so I made a simpler version of the problem. Any clue on how to do this?
If you comment on this, please be nice, I am a beginner and people was rude in the past,if you have nothing important to say, do not be mean/do not comment.
Well, the first problem with your current version is it only reads one integer. However problem states that each digit is on a separate line. The first approach may be to just replace that scanf with a loop and keeping multiplying by 10 and accumulating until end of file. Then the rest of the program would work fine.
A more advanced approach will be to use an array to store the digits. An integer can hold a very limited number of digits whereas you are only bounded with the size of available memory using array.
So in the reading loop rather than storing digits in an integer, you can store digits in an array (which could be fixed size because an upper limit is given). But for the rest of the program you should change the calculation to use digits in the array instead of the regular integer arithmetic.
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.
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.
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.
I was solving a puzzle, where im required to find the largest Prime Factor of a composite number entered by the user.
I thought of something and have tried it out, but it doesn't manage to detect the largest prime factor amongst the factors of the composite number.
I'm appending my code below, I'd be grateful if anyone could help me out here to get to detect the largest prime no. amongst the factors and print it.
// Accept a composite number from user and print its largest prime factor.
#include<stdio.h>
void main()
{
int i,j,b=2,c;
printf("\nEnter a composite number: ");
scanf("%d", &c);
printf("Factors: ");
for(i=1; i<=c/2; i++)
{
if(c%i==0)
{
printf("%d ", i);
for(j=2; j<=i/2; j++) //since a numbr cand be divisible by a number greated than its half
{ if(i%j > 0)
b = i;
else if(i==3)
b = 3;
}
}
}
printf("%d\nLargest prime factor: %d\n", c, b);
}
The trick is, find the smallest prime factor, and divide the composite number c by it to obtain the largest prime factor.
The trick is to find the smallest factor F (starting from 2) where C / F is prime. Then, C / F will be the largest prime factor of C.
Edit: It looks like you also want to list all the factors. The problem is, in your inner loop that tests for primality, you set the largest prime to i for numbers that are divisible with anything. In other words, try something like this:
is_prime = true;
for (j = 2; j <= x / 2; j++) {
if (i % j == 0)
is_prime = false;
}
if (is_prime)
largest_prime = x;
Note that you could actually stop sooner than x divided by 2. You could stop at the square root of x. However, the sqrt() function in <math.h> is a bit messy to work with in your case because it works with floating point numbers, not integers.
To find the prime factorization, you'd normally find all the factors between 2 and sqrt(N). You'd divide the composite by each of those to obtain the rest of the factors. Then recurse to find the prime factors of each of those.
When you're done, you'll have a list of all the prime factors. Getting the largest item in the list should be fairly trivial.
In your inner loop, you're setting b = i if there does exist a number that isn't a factor of i. You need to set b = i if there doesn't exist a number that is a factor of i.
(by "number", I mean "an integer between 2 and sqrt(i)" of course)
Factorization is a classic number theory problem. You can find many factorization algorithms in number theory textbooks. Some of them are available on wiki http://en.wikipedia.org/wiki/Integer_factorization
Hey thanks for the input friends, i worked out something and now the program prints the greatest prime factor of the composite number ,provided that the composite number is lesser than 52, while for higher ranges above this, it doesn't print the right output.
I'm Appending the code, please see if you guys could help me around
#include<stdio.h>
void main()
{
int i,j,b=2,c;
printf("\nEnter a composite number: ");
scanf("%d", &c);
printf("Factors: ");
for(i=1; i<=c/2; i++)
{
if(c%i==0)
{
printf("%d ", i);
for(j=1; j<=i; j++) //since a numbr cand be divisible by a number greated than its half
{ if(i%j > 0)
b = i; //b stores the largest prime factor
if(b%3==0)
b = 3;
else if(b%2==0)
b=2;
else if(b%5==0)
b=5;
}
}
}
printf("%d\nLargest prime factor: %d\n", c, b);
}
In Python, Something like this will do:
import math
import itertools
# largest prime factor of a composite number
def primality(num):
for i in range(2,int(math.sqrt(num))+1):
if num%i ==0:
return 0
return 1
if __name__ == '__main__':
number = 600851475143
for i in itertools.count(2,1):
if number%i == 0:
if number%10 in [7,9,1,3] and primality(number/i):
print number/i
break
What I have done to check primality is the neat square root technique.