I have an assignment to write a code that prints out all prime numbers between 1-100. I am looking at different programs to get an idea on what to do and keep running into i.e. "if (x%c == 0)".
Now I can't find out what the "x%c" means. I've looked around a lot and can't find any good answers anywhere. Possibly because of searching for the wrong thing. What exactly does that do in the following code?
#include<stdio.h>
int main()
{
int n, i = 3, count, c;
printf("Enter the number of prime numbers required\n");
scanf("%d",&n);
if ( n >= 1 )
{
printf("First %d prime numbers are :\n",n);
printf("2\n");
}
for ( count = 2 ; count <= n ; )
{
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
if ( c == i )
{
printf("%d\n",i);
count++;
}
i++;
}
return 0;
}
It is the modulo operation.
https://en.wikipedia.org/wiki/Modulo_operation
It is the remainder, if you do a division in integer space.
for example:
3 % 3 = 3 mod 3 = 0
means if you divide 3 by 3 you get one and the remainder is 0.
If the division leaves no remainder the first number is a multiple of the second.
That means it is not a prime (if the number you divide with is not 1 or the same number)
A full example
15 % 2 = 1
15 % 3 = 0
15 is no prime
"percentage in-between variables" is the operator for finding the remainder in C.
For example, if x = 10 and y = 4, then, x % y would be 2.
for ( c = 2 ; c <= i - 1 ; c++ )
{
if ( i%c == 0 )
break;
}
In the code snippet above, we will break out of this loop when a value of c is reached such that i is divisible by c i.e. i when divided by c gives 0 as the remainder.
Related
who can assess here?
I need a step-by-step explanation of this program, in particular, I'm interested in this line of code:
for(i = n-((n+1) % 2); i>=1; i-=2)
#include <stdio.h>
int main()
{
int i, n;
scanf("%d",&n);
for(i = n-((n+1) % 2); i>=1; i-=2)
{
if(i%2==1)
printf("%d ", i);
}
return 0;
}
This expression
n-((n+1) % 2)
yields the closest odd number that is equal to or less than n.
For example if n is an even number for example is equal to 2 then the expression will be equal to the odd number 1.
That is you will have in this case
2 - ( ( 2 + 1 ) % 2 )
that is equivalent to
2 - ( 3 % 2 )
that in turn is equivalent to
2 - 1
If n is an odd number for example equal to 3 then the expression will be equal to 3.
So subtracting 2 as
i-=2
you will have always an odd number.
Thus this statement in the body of the for loop
if(i%2==1)
printf("%d ", i);
outputs positive odd numbers in the descending order.
For example if n is equal to 10 then i will be initially equal to 9 and the loop outputs
9 7 5 3 1
The if statement is redundant. You could just write
printf("%d ", i);
Link to CodeChef problem MAXSC
Attempted solution:
#include<stdio.h>
int main()
{
long long int n, t, k, i, j, max[701], a[701][701], sum, flag;
scanf( "%lld", &t );
for( k = 0 ; k < t ; k++ )
{
scanf( "%lld", &n );
for( i = 1 ; i <= n ; i++ )
{
for( j = 1 ; j <= n ; j++ )
{
scanf( "%lld", &a[i][j] );
if( j == 1)
max[i] = a[i][1];
if( a[i][j] > max[i] )
max[i] = a[i][j];
}
}
sum = 0, flag = 0;
for( i = 1 ; i <= n-1 ; i++ )
{
if( max[i] < max[i+1])
sum = sum + max[i];
else
{
flag = 1;
break;
}
}
if(flag == 1)
printf("-1\n");
else
{
sum = sum + max[n-1];
printf("%lld\n", sum );
}
}
}
Compute the maximum possible value of E1 + E2 + ... + EN. If it's impossible to pick the elements E1, E2, ..., EN, print -1 instead.
Constraint:
Code should pick N elements, one from each sequence; let's denote the element picked from sequence Ai by Ei. For each i (2 ≤ i ≤ N), Ei should be strictly greater than Ei-1.
Does this constraint mean we have to choose max element from each line?
If you look at example given:
Example Input:
1
3
1 2 3
4 5 6
7 8 9
Output:
18
Explanation
Example case 1: To maximize the score, pick 3 from the first row, 6 from the second row and 9 from the third row. The resulting sum is E1+E2+E3 = 3+6+9 = 18.
If you notice they have mentioned "maximize".
Though my code finds the max, it isn't being accepted.
why is this code not being accepted?
Code's logic is flawed. When max[i] < max[i+1] is false, it sets flag = 1; instead of considering other elements from a[i].
Does this constraint mean we have to choose max element from each line?
No. The goal is a maximal sum, not a sum of maximums.
// if( max[i] < max[i+1])
if(max[i] < max[i+1])
sum = sum + max[i];
else {
flag = 1;
break;
}
The solution lies in tying other elements. Even if that fails, perhaps a prior selection should be changed. Recursion may be employed or other analysis. I think it would make sense to first sort each row of data to avoid this code taking n*n run-time. It should be trivial to code a n*n solution (trying every combination).
As this is homework, leave to OP to develop the solution.
1
3
6 10 12
4 5 7
8 9 10
-1
but output should be 6+7+10=23.
question is given Ei should be strictly greater than Ei-1
1
3
1 2 3
4 5 6
7 8 9
Output is 3+6+9=18 means 3<6 and 6<9 which satisfy the above problem
3
6 10 12
4 5 7
8 9 10
Output is 6+7+10=23 means 12<7 which is false and 6<7 which is true and 7<10 also true so sum=23.
3
8 9 10
11 12 13
10 5 9
Output is -1 because 10<13 is true but 13 is not less than 10 or 5 or 9 which is false hence output is -1.
Hi so I am using C code and trying to create a table where the number gets incremented in multiples of 5 starting from 1 to 5 to 10 to... all the way until the user's input. What I've gotten so far is that it starts at 1 and then increases the number by 5 like 1 to 6 to 11 to 16... until it gets to where it can't increase the number by 5 anymore without going above the user's input. Could someone help me set up the for loop better?
Here's the segment of my code I'm talking about:
else //run this statement if the user inputs a number greater than 14
{
printf("Number Approximation1 Approximation2\n-----------------------------------------------------\n"); //prints the header for second table
for ( i = 1; i <= n; i += 5 )
{
printf("%d %e %e\n", i, stirling1( i ), stirling2( i )); //calls functions to input approximate factorials
}
}
So with this code if I input n as 28, I get i to increment from 1 to 6 to 11 to 16 to 21 to 26.
What I want the code to do if I input n as 28 is increment i from 1 to 5 to 10 to 15 to 20 to 25 to 28.
Thanks in advance!
Try this:
{
printf("Number Approximation1 Approximation2\n-----------------------------------------------------\n"); //prints the header for second table
printf("%d %e %e\n", i, stirling1( 1 ), stirling2( 1 ));
for ( i = 5; i <= n; i += 5 )
{
printf("%d %e %e\n", i, stirling1( i ), stirling2( i )); //calls functions to input approximate factorials
}
}
This will print values for 1, 5, 10, 15, 20... and so on
Note that, besides an extra line of code, its faster than adding an "if" inside the loop.
I added two if statements which would help you deal with the special cases of having statements printed at i = 1 and i = n besides having the statement printed every 5.
else //run this statement if the user inputs a number greater than 14
{
printf("Number Approximation1 Approximation2\n-----------------------------------------------------\n"); //prints the header for second table
for ( i = 1; i <= n; i += 5 )
{
printf("%d %e %e\n", i, stirling1( i ), stirling2( i )); //calls functions to input approximate factorials
if (i == 1){
//when it iterates at the end of this loop, i = 5.
//In your example, you will get i from 1 to 5 to 10 up to 25 etc.
i = 0;
}
if ( (i + 5) > n){
// for the next loop, it will check if i will exceed n on the next increment.
// you do not want this to happen without printing for n = i.
//In your case if n = 28, then i will be set to 23, which will then increment to 28.
i = n - 5;
}
}
}
There are probably other more elegant ways of achieving this, but this is just a simple example of what you could try.
Can anyone explain to me how does this loop works? I understand that the first operator counts its remainder, the second counts its division result, but I can't understand how does it sum them using the loop? Here's the code:
// Calculate the sum of the digits of the number N.
int N, S, Z;
S = 0;
printf("Input N\n");
scanf("%d", &N);
while(N != 0) {
Z = N % 10;
N = N / 10;
S = S + Z;
}
printf("Sum = %d\n", S);
This while loop adds all the digit of your number referred in by N. It add's all the digit by taking remainder of number when divided by 10. And everytime, it eliminates the last digit of the number. So if your number is 326, it will work like:
326 != 0
Z = 6
N = 32
S = 6
32 != 0
Z = 2
N = 3
S = 8
3 != 0
Z = 3
N = 0
S = 11
0 == 0 come out of loop
print value of S i.e. 11
It's basically a sum of digits of an integer number.
Example:
input ==> 1234
output ==> 4+ 3+ 2 + 1 = 10
Code Break down:
Initialize S [sum] to 0.
Loop:
Z = N % 10; , store the remainder of N after %10 into Z.
N = N / 10; , divide the contents on N by 10 and store the result back in N.
S = S + Z;, sum the content of S with the value in Z.
after that, check the modified value of N is 0 or not. If not, continue [1,2,3..)
Suggestion:
Always check the success of scanf("%d", &N);. If by any chance, scanf() fails, your code is trying to access uninitialized variable N, which may very well lead to undefined behaviour.
The loop will execute until the n value become zero. For example
N=123
Then the first time values of the variables is
Z:3 : N:12 : S:3
Second time
Z:2 : N:1 : S:5
Third time
Z:1 : N:0 : S:6
Finally the answer of S will be 3+2+1=6.
Let's for a example take 657:
Z = N % 10; // This line will store 7 in Z
N = N / 10; // this line will convert N to 65
S = S + Z; // and finally this line will add 0+7
Question: 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
So, I was trying to do exercise 5 on project euler and I came out with this code:
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main () {
int n, fnd = FALSE, count, i;
for (i = 1; fnd == FALSE; i++) {
count = 0;
for (n = 1; n <= 20; n++) {
count += i % n;
}
printf ("testing %d, count was: %d\n", i, count);
if (count == 0) {
fnd = TRUE;
printf ("%d\n", i);
}
}
return 0;
}
I believe my apporach is correct, it will surely find the number which is divisible by 1 to 20. But it's been computing for 5 minutes, and still no result. Is my approach correct? If yes, then is there another way to do it? I can't think on another way to solve this, tips would be very much appreciated. Thank you in advance.
EDIT:
So, based on the advice I was given by you guys I figured it out, thank you so much!
So, it's still brute force, but instead of adding 1 to the last number, it now adds 2520, which is the LCM of 1 to 10. And therefore, calculating if the sum of the remainders of the multiples of 2520 divided from 11 to 20 was 0. Since 2520 is already divisible by 1 to 10, I only needed to divide by 11 to 20.
#include <stdio.h>
#define TRUE 1
#define FALSE 0
int main () {
int n, fnd = FALSE, count, i;
for (i = 2520; fnd == FALSE; i = i + 2520) {
count = 0;
for (n = 11; n <= 20; n++) {
count += i % n;
}
printf ("testing %d, count was: %d\n", i, count);
if (count == 0 && i != 0) {
fnd = TRUE;
printf ("%d\n", i);
}
}
return 0;
}
Thank you so much, I wouldn't solve it without your help : )
PS: It now computes in less than 10 secs.
Your approach is taking too long because it is a brute-force solution. You need to be slightly clever.
My hint for you is this: What does it mean for a number to be evenly divisible by another number? Or every number below a certain number? Are there commonalities in the prime factors of the numbers? The Wikipedia page on divisibility should be a good starting point.
Hint: You should look up "least common multiple".
Next hint:
The answer is the least common multiple (LCM) of the numbers 1, 2, 3, ..., 20.
LCM of n numbers can be found sequentially: if LCM(1, 2) = x, than LCM(1, 2, 3) = LCM(x, 3); if LCM(1, 2, 3) = y, than LCM(1, 2, 3, 4) = LCM(y, 4) etc. So it's enough to know how to find LCM of any 2 numbers.
For finding LCM of 2 numbers we can use the following formula: LCM(p, q) = pq/GCD(p, q), where GCD is the greatest common divisor
For finding GCD, there is a well-known Euclid's algorithm (perhaps the first non-trivial algorithm on the Earth).
I think you should start by computing the prime factors of each number from 2 to 20.
Since the desired number should be divisible by each number from 1 to 20, it must also
be divisible by each prime factor of those numbers.
Furthermore, it is important keep track of the multiplicities of the prime factors.
For example, 4 = 2 * 2, hence the desired number must be divisible by 2 * 2.
Something I quickly baked with Python 3:
primary_list = []
for i in range(2, 4097):
j = i
k = 2
delta_list = primary_list[0:]
alpha_list = []
while j > 1:
if j % k == 0:
j /= k
alpha_list.append(k)
k = 2
else:
k += 1
for i in alpha_list:
try:
delta_list.remove(i)
except:
primary_list.append(i)
final_number = 1
for i in primary_list:
final_number *= i
print(final_number)
This computes in mere seconds under a slow machine. Python is very good with abstract numbers. The best tool for the job.
The algorithm is relatively simple. We have a basic list primary_list where we store the multiples of the numbers. Then comes the loop where we estimate the range of numbers that we want to compute. We use a temporary variable j as a number that can be easily divided, chopped and conquered. We use k as the divisor, starting as 2. The delta_list is the main working copy of the primary_list where we take apart number after number until only the required "logic" is left. Then we add those numbers to our primary list.
1: 1
2: 2 1
3: 3 1
4: 2 2 1
5: 5 1
6: 2 3 1
7: 7 1
8: 2 2 2 1
9: 3 3 1
10: 2 5 1
The final number is found by multiplying the numbers that we have in the primary_list.
1 * 2 * 3 * 2 * 5 * 7 * 2 * 3 = 2520
As said, Python is _really_ good with numbers. It's the best tool for the job. That's why you should use it instead of C, Erlang, Go, D or any other dynamic / static language for Euler exercises.
I solved it using C. Below is the algorithm!
#include <stdio.h>
#include <stdio.h>
int main()
{
int i;
int count;
for(i=21;i>0;i++)
{ count = 0;
for( int j=2;j<21;j++)
{
if (i%j!=0)
break;
count++;
}
if (count==19)
break;
}
printf("%d\n",i);
return 0;
}
Just some thoughts about above comments,
#pg190 you say " it really only needs to be divisible by the primes between 1 and 20, i.e. 2, 3, 5, 7, 11, 13, 17, 19."
take 9699690, does not devide by all value from 1-20.
So this might be a good solution,
Given the number set [1-20]
The Least Common Multiple can be computed as follows.
Ex. For numbers 2,6,9
Express them in prime multiplications
2 2
6 2 3
9 3 3
LCM = multiple of highest power of each prime number.
= 2*3^2 = 18
This can be done to the problem in hand by expressing each number as prime multiplication
and then do this math.
$num=20;
for($j=19;$j>1;$j--)
{
$num= lcm($j,$num);
}
echo $num;
function lcm($num1, $num2)
{
$lcm = ($num1*$num2)/(gcd($num1,$num2));
return $lcm;
}
function gcd($n1,$n2)
{
$gcd=1;
$min=$n1;
if($n1>$n2)
{
$min=$n2;
}
for($i=$min;$i>1;$i--)
{
if($n1%$i==0 && $n2%$i==0)
{
$gcd*=$i;
$n1/=$i;
$n2/=$i;
}
}
return $gcd;
}
solved in php