How to check if a int var contains a specific number
I cant find a solution for this. For example: i need to check if the int 457 contains the number 5 somewhere.
Thanks for your help ;)
457 % 10 = 7 *
457 / 10 = 45
45 % 10 = 5 *
45 / 10 = 4
4 % 10 = 4 *
4 / 10 = 0 done
Get it?
Here's a C implementation of the algorithm that my answer implies. It will find any digit in any integer. It is essentially the exact same as Shakti Singh's answer except that it works for negative integers and stops as soon as the digit is found...
const int NUMBER = 457; // This can be any integer
const int DIGIT_TO_FIND = 5; // This can be any digit
int thisNumber = NUMBER >= 0 ? NUMBER : -NUMBER; // ?: => Conditional Operator
int thisDigit;
while (thisNumber != 0)
{
thisDigit = thisNumber % 10; // Always equal to the last digit of thisNumber
thisNumber = thisNumber / 10; // Always equal to thisNumber with the last digit
// chopped off, or 0 if thisNumber is less than 10
if (thisDigit == DIGIT_TO_FIND)
{
printf("%d contains digit %d", NUMBER, DIGIT_TO_FIND);
break;
}
}
Convert it to a string and check if the string contains the character '5'.
int i=457, n=0;
while (i>0)
{
n=i%10;
i=i/10;
if (n == 5)
{
printf("5 is there in the number %d",i);
}
}
Related
I'm understand only the code, but not it's core concept anyone explain about its flow chart and Algorithm
why we use i<=n/2 in this code is there any way to use i<=n
#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
for (i = 2; i <= n / 2; ++i) {
// condition for non-prime
if (n % i == 0) {
flag = 1;
break;
}
}
if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}
return 0;
}
Suppose n is composite. Then n=ab for some integers a,b>1. Your first loop checks if a or b is an integer in the range [2, n/2]. If that loop never finds a factorization like that, it must be that one of the factors (if it exists) is greater than n/2. If it is greater than n/2, the other factor must be less than 2. The only such factorization is n=1n, in which case n is in fact a prime. Thus it suffices to check only factors up to n/2.
PS: I deliberately don't specify what I mean when n is odd. That's left as an exercise for you to fill in.
PPS: You can easily do a lot better than stopping at n/2. Hint: What happens when both factors are the same?
In the code you are using i <= n / 2 because for any numbers, you can't divide itself by another number greater than its half.
Let's take 29 for example (and use int, so not floating part).
29 / 2 = 14
29 / 3 = 9
29 / 4 = 7
29 / 5 = 5
...
29 / 14 = 2
29 / 15 = 1
29 / 16 = 1
...
Here, you see that after 14 (the half of 29), all the results are 1.
If you wish to, you can even use this formula n > i * i. Let me explain with this example. Here, we should stop at i = 5 because 29 < 6 * 6
29 / 2 = 14
29 / 3 = 9
29 / 4 = 7
29 / 5 = 5
===== END HERE (but let's continue to see what happens) =====
29 / 6 = 4
29 / 7 = 4
29 / 8 = 3
...
You can see that after 5, the results become smaller than the index, so you are just recalculating something that you have already calculated. It avoids timeouts on big numbers.
The program must accept an integer N with even number of digits as the input.
The program must reverse every two digits in N and print the modified N as the output.
Boundary Condition(s): 10 <= N < 10^16
Input Format: The first line contains N.
Output Format: The first line contains the modified N.
Example Input/Output 1:
Input: 214587
Output: 125478
Explanation: The first two digits are 2 and 1 which are reversed as 1 and 2. The second two digits are 4 and 5 which are reversed as 5 and 4. The third two digits are 8 and 7 which are reversed as 7 and 8.
Example Input/Output 2:
Input: 504786
Output: 57468
I have proceeded in a logic of printing the values inside a while loop by printing b/10 and b%10; where the output should be reversed and I am stuck in it, please help in my logic how to proceed further thank you.
scanf("%d",&a);
while(a>0) {
b=a%100;
printf("%d%d",b/10,b%10);
a=a/100;
}
As I noted in three comments (1, 2, 3), I think you need to use recursion, and some care. Here is code that works, and a test harness (which is bigger than the code being tested) demonstrating that it works:
#include <inttypes.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static bool reverse_digit_pairs(uint64_t value)
{
uint64_t b = value % 100;
uint64_t v = value / 100;
if ((v > 0 && v < 10) || (v == 0 && b < 10))
return false;
int t = b / 10; // tens
int u = b % 10; // units
bool ok = true;
if (v >= 10)
ok = reverse_digit_pairs(v);
if (ok)
{
if (u == 0 && v == 0)
printf("%d", t);
else
printf("%d%d", u, t);
}
return ok;
}
static void test_reverse_digit_pairs(uint64_t v)
{
printf("V: %20" PRIu64 " = ", v);
if (!reverse_digit_pairs(v))
{
fprintf(stderr, "Odd number of digits in %" PRIu64 "\n", v);
printf("bogus input");
}
putchar('\n');
fflush(0); // Ensure standard output (and standard error) are flushed.
}
int main(void)
{
test_reverse_digit_pairs(UINT64_C(214587)); // 125478 per question
test_reverse_digit_pairs(UINT64_C(504786)); // 57468 per question
test_reverse_digit_pairs(UINT64_C(5047000086)); // Pairs of zeros
test_reverse_digit_pairs(UINT64_C(5047900086)); // Pair of zeros
test_reverse_digit_pairs(UINT64_C(1234567890123456)); // 16 digits
test_reverse_digit_pairs(UINT64_MAX); // 20 digits
test_reverse_digit_pairs(UINT64_C(123456789012345)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(0)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(1)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(9)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(10)); // 2 digits
test_reverse_digit_pairs(UINT64_C(99)); // 2 digits
test_reverse_digit_pairs(UINT64_C(100)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(999)); // Odd digits - failure
test_reverse_digit_pairs(UINT64_C(1000)); // 4 digits
test_reverse_digit_pairs(UINT64_C(1098)); // 4 digits
test_reverse_digit_pairs(UINT64_C(1234)); // 4 digits
return 0;
}
The output I get from it is:
V: 214587 = 125478
V: 504786 = 57468
V: 5047000086 = 574000068
V: 5047900086 = 574090068
V: 1234567890123456 = 2143658709214365
V: 18446744073709551615 = 81447644707390556151
Odd number of digits in 123456789012345
V: 123456789012345 = bogus input
Odd number of digits in 0
V: 0 = bogus input
Odd number of digits in 1
V: 1 = bogus input
Odd number of digits in 9
V: 9 = bogus input
V: 10 = 1
V: 99 = 99
Odd number of digits in 100
V: 100 = bogus input
Odd number of digits in 999
V: 999 = bogus input
V: 1000 = 100
V: 1098 = 189
V: 1234 = 2143
The test cases for the numbers with 1 to 4 digits were necessary to flush out some issues. I'm not completely happy with the first condition in reverse_digit_pairs(), but I didn't get the output I think is required when I tried some simplifications.
I have these variables:
int dividend;
int divider;
And I have the function :
Divisibility7 (int num);
Those two variables will be at the main function, and the user will be asked to enter the dividend and divider, but in case the user enter the divider 7, then, the function above will be called.
The problem is that I have to follow specific criteria to do this. So let's say the user will enter with the dividend 7203. This happen :
I. Get the last digit of the number.
Last digit: 3
Ii. Multiply the last digit by 2
3 x 2 = 6
Iii. Get the value of the initial number, without the last digit.
720
Iv. Subtract the initial value without the last digit from the multiplication result.
fabs (720 - 6) = 714
V. Repeat the process until the result is a value less than or equal to 70
Vi. Compare the result with the table of contents (0, 7, 14, 21, 28, 35, 42, 49, 54, 63, 70) for
Determine whether or not the number is divisible by 7
Code :
int res;
int x;
int y;
int Divisibility7(int num) {
int res;
int x;
int y;
int z;
while(num > 70) {
x = num % 10; // get the last digit from the number
y = x * 2; // multiply the last digit by 2;
z = num/10; // get the first digits from the number
fabs(z - y); // subtract the first digits with the last digits;
}
}
In the part of the while, the final fabs(z-y) returns what I want, to be the first digits subtracting the last number, but the problem is that the while stop there, I have to do something to make this while go till 70 or less.
PS : I need to check if the final number from the iterations, it's a number multiplied by 7, how can I do that ? And I can't use mod for this.
You have not changed num in your while loop . Also you do no return the value . Hope the following code will be ok for you .
int Divisibility7(int num) {
int res,x,y,z;
while(num > 70) {
x = num % 10; // get the last digit from the number
y = x * 2; // multiply the last digit by 2;
z = num/10; // get the first digits from the number
num = abs(z - y); // subtract the first digits with the last digits;
}
if(num == 0 || num == 7 || num == 14 || num == 21 || num == 28 || num == 35 || num == 42 || num == 49 || num == 54 || num == 63 || num == 70) {
return 1;
}
else {
return 0;
}
}
Not sure, but I think this is what are you trying to do:
int main (void)
{
int number, lastDigitMultiplied;
scanf("%d", &number);
while(number > 70){
//get the last digit and multiply it by 2
lastDigitMultiplied = (number % 10) * 2;
//subtract the initial value without the last digit from the multiplication result.
number = number / 10 - lastDigitMultiplied;
}
if(abs(number) % 7 == 0)
printf("The result is %d and it is a multiple of 7", number);
else
printf("The result is %d and it is not a multiple of 7", number);
return 0;
}
for divisibility against 7, if you have a positive large bigint already formatted as a string, don't waste time with the regular method doing it 1 digit at a time.
powers of 10, mod 7, repeats every 6 rounds :
10^1 % 7 = 3 10^7 % 7 = 3 10^13 % 7 = 3
10^2 % 7 = 2 10^8 % 7 = 2 10^14 % 7 = 2
10^3 % 7 = 6 10^9 % 7 = 6 10^15 % 7 = 6
10^4 % 7 = 4 10^10 % 7 = 4 10^16 % 7 = 4
10^5 % 7 = 5 10^11 % 7 = 5 10^17 % 7 = 5
10^6 % 7 = 1 10^12 % 7 = 1 10^18 % 7 = 1
meaning, the effects of the digits mod 7 stay identical as long as they're in chunks of 6 digits at a time.
the largest multiple of 6-digits supported by double precision FP to full integer precision would be 12-digits at a time.
So the way to do it is to right-align the digits by padding leading edge zeros to ensure string length is a multiple of 12. Then simply add the digits onto each other, performing a single mod % 7 operation once every 9000 or so rounds of the addition loop
—- (that's when you run up against 2^53 limit; 9007 rounds if u wanna be pedantic about it)
example :
x = 71400535477047763120175175402859619447790
02233464423375355339031113233806609150957
x % 7 = 4
now try summing up chunks of 12 :
007140053547704776312017517540285961944779
002233464423375355339031113233806609150957
007140053547 7140053547
704776312017 711916365564
517540285961 1229456651525
944779002233 2174235653758
464423375355 2638659029113
339031113233 2977690142346
806609150957 3784299293303
----------------------------
3784299293303 % 7 = 4
it works exactly the same for any multiples of 6 : e.g. 6, 18, 24, and 30 --
00714005354770477631201751754
02859619447790022334644233753
55339031113233806609150957
312017 312017
517540 829557
285961 1115518
944779 2060297
002233 2062530
464423 2526953
375355 2902308
339031 3241339
113233 3354572
806609 4161181
150957 4312138
007140 4319278
053547 4372825
704776 5077601
----- -------
_ 5077601 % 7 = 4
00000000714005354770477631201
75175402859619447790022334644
23375355339031113233806609150957
464423375355339031 464423375355339031
113233806609150957 577657181964489988
000000007140053547 577657189104543535
704776312017517540 1282433501122061075
285961944779002233 1568395445901063308
---------------------------------------
1568395445901063308 % 7 = 4
00000000000000714005354770477
63120175175402859619447790022
33464423375355339031113233806
609150957
339031113233806609150957 339031113233806609150957
000000000000007140053547 339031113233813749204504
704776312017517540285961 1043807425251331289490465
944779002233464423375355 1988586427484795712865820
---------------------------------------------------
1988586427484795712865820 % 7 = 4
000000007140053547704776312017517
540285961944779002233464423375355
339031113233806609150957
000000007140053547704776312017 7140053547704776312017
517540285961944779002233464423 517540293101998326707009776440
375355339031113233806609150957 892895632133111560513618927397
892895632133111560513618927397 % 7 = 4
i am working on a program where the input is an ID of 9 numbers :
program checks if the id is correct or not by :-
checking if the string is formed by numbers only .
every number has a weight of 1 or 2 so it should be 1 2 1 2 1 2 1 2
1
multiply the weight and the number
if the number is bigger than 9 then add the numbers forming it .
if the number is from multiplication of 10 then the ID is correct ..
example :-
1 7 9 3 7 9 2 5 0-ID
1 2 1 2 1 2 1 2 1-Weight
1 14 9 6 7 18 2 10 0-num x weight
1 5 9 6 7 9 2 1 0-(4)
sum = 40 then it is a correct ID.
I wrote most of it but then i noticed that it has to be a string . so my questions are :
is there a way to put a string into an array?as doing it with an
array is way easier.
how do i locate a place in a string ? like if i want the third
character in a string how do i locate it?.
and here is the code that i did it does not work yet and it needs alot of changes but i guess i will put it anyways :-
#include<stdio.h>
#define N 9
void input(int num[N]);
int check(int num[N]);
int main()
{
int num[N],a;
input(num);
a = check(num);
if (a = 1)
printf("ID is correct");
else printf("ID is NOT correct");
}
void input(int num[N])
{
int i;
printf("Enter your ID (9digits) :-");
for (i = 0;i < N;i++)
scanf("%d",num[i]);
}
int check(int num[N])
{
int w[N] = { 1,2,1,2,1,2,1,2,1 },wxnum[N],i,tota[N],sum,g;
for (i = 0;i < N;i++)
wxnum[i] = num[i] * w[i];
for (i = 0;i < N;i++)
{
if (wxnum[i] > 9)
tota[i] = wxnum[i] / 10 + wxnum[i] % 10;
else tota[i] = wxnum[i];
}
sum = tota[0] + tota[1] + tota[2] + tota[3] + tota[4] + tota[5] + tota[6] + tota[7] + tota[8];
g = sum % 10;
if (g = 0)
return 1;
else
return 0;
}
Thanks everyone for your help.
You can get a string by doing
/*N is defined as 9 in your code.*/
/*Considering there is always a '\0' in every string, we should allocat N + 1 slot for your nine numbers and the extra '\0'.*/
char chStr[N + 1];
scanf("%s", chStr);
After you got the string, you can take advantage of the values of charactor '0' - '9' (their values are from 48 to 57 correspondingly) in ASCII table, and easily transfer the charactors into integers by doing:
int i = 0;
for (i = 0; i < N; i++)
{
chStr[i] = chStr[i] - '0';
}
If you are restrict on the type, you can transfer these char values into int values by adding extra two lines:
int num[N];
int i = 0;
for (i = 0; i < N; i++)
{
chStr[i] = chStr[i] - '0';
num[i] = (int) chStr[i];
}
Please note that my code didn't check the validation of user input. To make it more secure, you can use
scanf("%9s", chStr);
to declare the maximum length that the user can input.
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