So I have this program and need it to write the output as "96 is 2^5 x 3^1" instead of 2x2x2x2x2x3.
int main() {
int i, n;
// Get the user input.
printf("Please enter a number.\n");
scanf("%d", &n);
// Print header.
printf("The prime factorization of %d is ", n);
// Loop through, finding prime factors.
int cur_factor = 2;
while (cur_factor < n) {
// Found a factor.
if (n%cur_factor == 0) {
printf("%d x ", cur_factor);
n = n/cur_factor;
}
// Going to the next possible factor.
else
cur_factor++;
}
// Prints last factor.
printf("%d.\n", cur_factor);
return 0;
What do I need to do?
Thanks
while (cur_factor < n) {
// Found a factor.
while (n%cur_factor == 0) {
n = n/cur_factor;
count++;
}
while(count--)
printf("%d x ", cur_factor);
count=0;
// Going to the next possible factor.
else
cur_factor++;
}
Use a variable power to keep track of the exponent and print it.
Also use a while loop to keep dividing n by cur_factor until n cannot be divided anymore by that factor.
int cur_factor = 2;
int power = 0;
while (cur_factor < n) {
// Found a factor.
while (n % cur_factor == 0) {
power++;
n = n/cur_factor;
}
// Going to the next possible factor.
if (power > 0)
printf("%d^%d x", cur_factor, power);
power = 0;
cur_factor++;
}
}
Related
This program is supposed to print the first x prime numbers, but I noticed that it was printing some non-prime numbers, such as 27 or 35.
I've been looking at it for hours and nothing seems to pop up. So please, if you know what's wrong, tell me.
#include <stdio.h>
int main(){
int i=0, cont=2, prim=2, quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
while(i<quant){
if(prim%cont!=0 && (cont>1 && cont<prim)){
cont++;
}
else if(prim%cont==0 && (cont>1 && cont<prim)){
prim++;
}
else if(prim%cont==0 && cont==prim){
printf("%d\n", prim);
prim++;
cont=2;
i++;
}
}
return 0;
}
UPDATE
Wow, ok, so after 7 years people still stumble upon this question.
In the last 7 years my coding ability has improved somewhat, and now I see how inefficient this program was. Just in case anyone might be trying to find the solution for this and the stumble upon this, here are three solutions much easier and better, and why they work.
Solution 1:
This first solution is very inefficient too, but it works, and is pretty simple to understand. Basically what you have to do is check if each number up to the upper limit is prime or not. To do so, just check if it is divisible by any number up to its square root.
Why its squared root? Because the square root squared is equal to the number, which means that if the number was not divisible up to its square root, it won't be divisible by any number above it, as for it to be divisible by it, it needs to multiply by a smaller number. For example, the squared root of 36 is 6, and 36 is divisible by 9, as 9*4=36. But since 9 is above 6 (which is the squared root), the number that multiplied by 9 gives us 36 is below, and as such, we have already seen that it is not prime, as we have already checked that 36 is divisible by 4. This being said, if no number below the squared root of a number is a natural dividend of the number, than that number is prime.
#include <stdio.h>
int isPrime(int num) {
for (int i = 2; i*i <= num; i++) {
if (num%i==0) {
return 0;
}
}
return 1;
}
void getPrimes(int num) {
int cont = 0;
for (int i = 2; cont < num; i++) {
if (isPrime(i)==1) {
printf("%d\n", i);
cont++;
}
}
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
This is inefficient as we are checking if the number is divisible by numbers that won't influence (more on this in the next solution).
Solution 2:
In this second solution, which is more elegant in my opinion, we give use to the Fundamental Theorem of Arithmetic, which states that any number greater than 1 is either a prime number itself, or can be represented by factorizing into the multiplication of prime numbers. This means that if a number is divisible by a non prime number, it is also divisible by the prime numbers that make it up, and thus we only need to check if the number in question is divisible by smaller prime numbers than itself. For this purpose, we store the prime numbers in an array.
#include <stdio.h>
void getPrimes(int num) {
int primes[num];
int cont = 1;
primes[0] = 2;
int current = primes[cont-1]+1;
while (cont < num) {
int before = current;
for (int i = 0; i < cont; i++) {
if (current%primes[i]==0) {
current++;
break;
}
}
if (before == current) {
primes[cont] = current;
cont++;
current++;
}
}
for (int i = 0; i < cont; i++) {
printf("%d ", primes[i]);
}
printf("\n");
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
Solution 3:
This final solution is a mix of the two above. Solution 1 checked numbers that weren't prime, having redundancy, and the solution 2 checked numbers above the square root, which can never be a dividend if the smaller numbers aren't. In this solution, we check if the number is divisible only by prime numbers below the squared root.
#include <stdio.h>
void getPrimes(int num) {
int primes[num];
int cont = 1;
primes[0] = 2;
int current = primes[cont-1]+1;
while (cont < num) {
int before = current;
for (int i = 0; (i < cont && primes[i]*primes[i] <= current); i++) {
if (current%primes[i]==0) {
current++;
break;
}
}
if (before == current) {
primes[cont] = current;
cont++;
current++;
}
}
for (int i = 0; i < cont; i++) {
printf("%d ", primes[i]);
}
printf("\n");
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
Comparing the execution times of each algorithm for 100 prime numbers, we obtain the following results
Algorithm 1
Algorithm 2
Algorithm 3
0.048 ms
0.068 ms
0.039 ms
Comparing to the algorithm of the original post which takes 0.599 ms, every one of these new solutions is more efficient (the worst being around 10x better), and actually calculates the real values.
Try this
#include<stdio.h>
int prime(int n)
{
int i, j, len=1, brk=0;
int list[200]={2};
for(i=2; i<=n; i++)
{
for(j=0; j<len; j++)
{
if(i%list[j]==0){
brk=1;
break;
}
else
{
brk=0;
}
}
if(brk==0)
{
list[len]=i;
len++;
}
}
for(i=0; i<len; i++)
printf("%d ",list[i]);
}
main()
{
int i, n;
scanf("%d",&n);
prime(n);
}
#PKDOJ If the series is set within 30. You can go blindly with the logic below. But nothing above that series. Adding i%11 clears the 77 as well. Not efficient
if ((i % 2) && (i % 3) && (i % 5)&&(i%7)&&(i%11))
Code:
int count = 0, quant = 5, i, j;
int flag = 0;
for(prim = 2 ; count <= quant ; prim ++) {
flag = 0;
for(j = 2; j < prim/2; j++) {
if(prim % j == 0) {
flag = 1;
break;
}
}
if(flag == 0) {
printf("%d\n", prim);
count++;
}
}
Update your code as:
while(i<quant){
if(cont<prim) {
if(prim%cont!=0) {
cont++;
} else {
prim++;
cont = 2; // restart cont
}
}
else if(prim%cont==0 && cont==prim){
printf("%d\n", prim);
prim++;
cont=2;
i++;
}
}
Simple way is to find is: if a number is not divisible by 2,3 & 5, its a prime number.
#include <stdio.h>
int main()
{
int num = 35;
int i = 5;
printf("1 2 3 5");
while (i <= num)
{
if ((i % 2) && (i % 3) && (i % 5))
{
printf(" %d",i);
}
i++;
}
printf("\n");
return 0;
}
I have this code in which I need to find all prime numbers from 2 to 1000 and need to print them out in groups of 5 in each line. How can I do that?
#include <stdio.h>
int main() {
int i, a, count;
printf("Prime numbers between 2 and 1000 are : \n");
for (i = 2; i < 1000; i++) {
count = 0;
for (a = 1; a <= i; a++) {
if (i % a == 0)
count++;
}
if (count == 2)
printf("%d\t", i);
}
return 0;
}
You can add a new counter to count the number of prime numbers printed until the current loop. If this counter value is divisable by 5, print a new line.
int main()
{
int i,a,count;
printf("Prime numbers between 2 and 1000 are : \n");
int cnt_prime = 0; // count the number of prime numbers until this loop
for (i=2;i<1000;i++)
{
count=0;
for (a=1;a<=i;a++)
{
if (i%a==0)
count++;
}
if (count==2) {
printf("%d\t", i);
cnt_prime++;
if (cnt_prime % 5 == 0) // print new line after each five numbers
printf("\n");
}
}
return 0;
}
There is another faster approach to find the prime numbers in a range. You can read about sieve of eratosthenes from here: https://www.geeksforgeeks.org/sieve-of-eratosthenes/
Maybe not the best answer, but you could add another counter-variable called prime_count and initialize it with value 0. Then each time you print a prime, you increment that variable. After printing a prime you then check wether prime_count is equal to 4. If that's the case you print a newline-character and reset prime_counter to 0.
The code could look something like this:
int main()
{
int i,a,count,prime_count=0;
printf("Prime numbers between 2 and 1000 are : \n");
for (i=2;i<1000;i++)
{
count=0;
for (a=1;a<=i;a++)
{
if (i%a==0)
count++;
}
if (count==2)
{
printf("%d\t",i);
prime_count++;
if (prime_count == 4)
{
printf("\n");
prime_count = 0;
}
}
}
return 0;
}
You can check till square root of N to verify prime no need to check till N it makes your code O(sqrt(n)) refer this for more info about the algorithm.You can have a variable called printCounter to check total elements printed on console when it become a multiple of 5 we can print a new line.
int main() {
int i, a, printCount = 0 ;
printf("Prime numbers between 2 and 1000 are : \n");
for (i = 2; i < 1000; i++) {
int isPrime = 1;
for (a = 2; a * a <= i; a++) {
if (i % a == 0){
isPrime = 0;
break;
}
}
if (isPrime == 1) {
printf("%d\t", i);
printCount++;
}
if(printCount%5 == 0){
printf("\n");
}
}
return 0;
}
I wrote this program to find prime numbers between 1 and 50000, and I still need to find how many prime numbers there is (I tried a lot of tricks but I did not succeed)
#include <stdio.h>
//int getValueFromUser();
void PrintListOfPrime(int value);
int main() {
int value = 23;
PrintListOfPrime(value);
return 0;
}
void PrintListOfPrime(int value) {
int ValueIsPrime; //ValueIsPrime is used as flag variable
printf("The list of primes: ");
for (int i = 2; i <= value; i++) {
ValueIsPrime = 1;
/* Check if the current number i is prime or not */
for (int j = 2; j <= i / 2; j++) {
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
if (i % j == 0) {
ValueIsPrime = 0;
break;
}
}
/* If the number is prime then print */
if (ValueIsPrime == 1)
printf("%d, ", i);
}
printf("\n");
}
I tried a lot of tricks but I did not succeed
If OP's code takes too long to ran, iterate to the square root of i, not up to i/2.
j <= i / 2 is very slow. Use j <= i / j instead.
Form a count and increment with every prime. #gspr
if (ValueIsPrime == 1) {
printf("%d, ", i);
prime_count++;
}
Bigger change yet even faster to "find prime numbers between 1 and 50000", research Sieve of Eratosthenes
Hello fast answer is to create a variable in main, int totaleOfPrimes = 0; for example.
then send it by reference to the fucntion :
Function declaration : void PrintListOfPrime(int value,int* counter);
Function call : void PrintListOfPrime(value,&totaleOfPrimes);
then Increment counter befor printing :
if (ValueIsPrime == 1){
(*counter)++;
printf("%d, ", i);
}
There is no need to iterate the loops for all numbers between 2 and value. You should consider only 2 and odd numbers.
The function can look the following way as it is shown in the demonstrative program below.
#include <stdio.h>
static inline size_t PrintListOfPrime( unsigned int n )
{
size_t count = 0;
printf( "The list of primes:\n" );
for ( unsigned int i = 2; i <= n; i = i != 2 ? i + 2 : i + 1 )
{
int isPrime = 1;
/* Check if the current number i is prime or not */
for ( unsigned int j = 3; isPrime && j <= i / j; j += 2 )
{
/*
* If the number is divisible by any number
* other than 1 and self then it is not prime
*/
isPrime = i % j != 0;
}
/* If the number is prime then print */
if ( isPrime )
{
if ( ++count % 14 == 0 ) putchar( '\n' );
printf( "%u ", i );
}
}
return count;
}
int main(void)
{
unsigned int n = 50000;
size_t count = PrintListOfPrime( n );
printf( "\n\nThere are %zu prime numbers up to %u\n", count, n );
return 0;
}
Run this code in C. It will return the value of a pi(x) function. It is basically the Prime counting function:
#include <stdio.h>
#define LEAST_PRIME 2
#include <math.h>
int main() //works for first 10000 primes.
{
int lower_limit = 2, no_of_sets;
// printf("NUMBER OF SETS: ");
// scanf("%d", &no_of_sets);
int remainder, divisor = 2, remainder_dump, upper_limit; //upper limit to be specified
//by user.
int i = 1;
// printf("SPECIFY LOWER LIMIT: ");
// scanf("%d", &lower_limit);
int number_to_be_checked = lower_limit;
printf("SPECIFY UPPER LIMIT: ");
scanf("%d", &upper_limit);
printf("2\t\t\t\t", number_to_be_checked);
//PRINTS 2.*/
do
{
remainder_dump = 1;
divisor = 2;
do
{
remainder = number_to_be_checked % divisor;
if (remainder == 0)
{
remainder_dump = remainder_dump * remainder; // dumping 0 for rejection.
break;
}
++divisor;
} while (divisor <= number_to_be_checked / divisor); // upto here we know number
is prime or not.
if (remainder_dump != 0)
{
++i;
printf("%d.\t\t\t\t", number_to_be_checked); //print if prime.
};
number_to_be_checked = number_to_be_checked + 1;
} while (number_to_be_checked <= upper_limit);
printf("\n pi(x) = %d \n", i);
//printf("pi function value is %f.", (i - 1) / (log(i - 1)));
float app;
app = upper_limit / (log(upper_limit));
float plot_value;
plot_value = (i) / app;
printf(" BETA FUNCTION VALUE ~ %f", plot_value);
return 0;
}
I'm writing a program to determine whether or not a given number is a prime number or a composite. My code below is what i have so far. I'm thinking that using a WHILE LOOP wouldn't be as efficient as a FOR LOOP but i may be wrong.
#include <stdio.h>
int main(int argc, const char* argv[]) {
int num, i;
printf("Enter a number you want to check:");
scanf("%d", &num);
if (num == 1) {
printf("%d is neither prime nor composite", num);
}
i = 2;
while (i <= num - 1) {
if (num % i == 0) {
printf("%d is composite\n\n", num);
break;
}
}
}
The program works with most even numbers but when I get to, say 9 I don't get a return because it's not dividing by three. Could i add into this WHILE LOOP to compensate or would i be easier to use a FOR LOOP?
I'm thinking that if i used a FOR LOOP i could start it off sort of like this.
for (i = 2, i <= num, i++) {
num % i == 0;
}
printf("%d is Composite", num);
}
you have forgotten to increase the index inside your loop
while (i <= num-1) {
if (num%i==0)
{
printf("%d is composite\n\n",num);
return; // test is finished
}
i++; // increase i by 1
}
printf("%d is prime number\n", num); // add this line to display the prime numbers also
EDIT
I just came to see your comment about the use of for loop :
for (i = 2; i < num; i++) // ① be careful of ; and , ② i<num not i<=num
{
if(num % i == 0) // if your num is dividable ==> not prime
{
printf("%d is Composite", num);
return 0; // return from the main func
}
}
printf("%d is prime number\n", num); // no divisor = no return = prime number
EDIT 2
Now let's talk about efficiency :
to determine whether the number is prime or not, you can iterate for less than even half of it, how ?
if p is the number and k is its divisor then :
p = k * n
if ( n > sqrt(p) && k > sqrt(p))
==> n * k > p
take any pair of divisors for any integer, both the divisors cannot be greater than the square root of the integer at the same time!
that's why you can iterate like this:
while (i <= sqrt(num)) {
if (num%i==0)
{
printf("%d is composite\n\n",num);
return; // test is finished
}
i++; // increase i by 1
}
So for your 10000 you only iterate 100 time! and not 5000 as you thought ;)
FURTHER
If you're really on a tight budget, you can check only for odd numbers greater than 2 :D, I mean if it was not dividable by 2 then it'll never be dividable by 4, 6, 8 ... skip them
Example :
if(num%2 == 0) // check for 2
{
printf("%d is composite\n\n",num);
return;
}
while (i <= sqrt(num)) // check only for odd # greater than 2
{
if (num%i==0)
{
printf("%d is composite\n",num);
return; // test is finished
}
i+=2; // increase i by 2
}
printf("%d is prime\n", num);
Where you wrote:
for (i = 2, i <= num, i++)
you want:
for (i = 2; i < num; i++)
you might also think about why this:
for (i = 2, i*i <= num, i++)
might be a big win...
Following the answer from #neal aise here to get prime factors:
I did:
/*neal aise's code*/
printPrimeFactors(int num) {
int i;
for (i = 2; i < sqrt(num); i=next_prime(i)) {
if (num %i){
printf("%d", i);
}
}
}
/*my code*/
int next_prime(int p){
int prime_found = 0;
while (!prime_found){
if (p <= 1)/* if low number comes in, then */
p = 2; /* next prime is always 2 (first prime) */
else
if ((p % 2) == 0) /* no even primes */
p++; /* make the number odd before test */
else
p += 2; /* get next odd numero to test */
prime_found = is_prime(p); /*check if number is prime*/
}
return (p);
}
int is_prime(int p){
int curr_num = 2; /* start divisor at 2 */
float stop_num = sqrt((float) p); /* no divisor > sqrt of number needed */
while(curr_num <= stop_num){
if ((p % curr_num) == 0) /* not prime if evenly divisible */
return (0);
else
curr_num++; /* increment divisor */
}
return(1); /* not evenly divisible, return prime */
}
How do I moddify the code in function
printPrimeFactors()
so it works as desired?
If you want "prime number generator", interfaces is ok to me. But your code limit the number of prime numbers.
meaningless interfaces is not valuable. it can write more simply.
#include <stdio.h>
int main() {
int n, m;
for (n = 1; n < 1000 /* specify your max */; n++) {
for (m = n-1; m > 1; m--)
if (n % m == 0) break;
if (m == 1)
printf("%d\n", n);
}
return 0;
}
There are a couple of logic errors:
if (num%i) // Change this to...
if ((num%i)==0) // num%i == 0 when i divides num, this 'i' is a prime factor.
Also, you will only print out roughly half of the prime factors by stopping at <sqrt(num). Either change the exit condition of the for loop to be i <= num:
for (i = 2; i <= num; i=next_prime(i)) { // note the <=
if (num %i){
printf("%d ", i);
}
}
Or the alternative, more efficient method. Note the factors will not be in order:
for (i = 2; i <= sqrt(num); i=next_prime(i)) {
if (num %i){
printf("%d %d ", i, num/i); // Print out the pair, since we stop at i<=sqrt(num)
}
}
Instead of x = sqrt(n_limit) and if(n < x), you can do it like if(n*n < n_limit). No need for expensive sqrt(), floats or casts.