Is there any method to organize "cycling" (looping) numbers in c++? - c++

I need to have a cycle of limited number (0 to 3) in an infinite loop. So I use this code:
int moveOp = 0;
while (1) {
//some operations with moveOp here
moveOp++;
if(moveOp>3) {
moveOp = 0;
}
}
But maybe there is a method to have a data type with which increment operator jumps to zero without hand written condition?

This would work:
moveOp = (moveOp + 1) % N;

if your NUM is power of 2 you can use the bitfields as well
struct {
unsigned moveOp:2;
}m;
m.moveOp++;

for(int i = 0; ; i = (i + 1) % 4) {
// your code goes here
}

I think Modulus operator is what you are looking for.
Following is the sample how you can use it:
int moveOp = 0;
int Num = 4;
while (1) {
++moveOp;
moveOp = moveOp%Num;
}

Related

Scrambled number when access array[10000]

I was looking for solution to question what is the 10001st prime number.
And i am done with the code :
int main() {
long long listNumber[10001];
long position = 1, divider = 0;
listNumber[0] = 2;
while(listNumber[10000] == 0) {
divider = 0;
listNumber[position] = listNumber[position-1] + 1;
while(listNumber[divider] <= sqrt(listNumber[position])) {
if(listNumber[position] % listNumber[divider] == 0) {
listNumber[position]++;
divider = 0;
} else divider++;
}
position++;
}
cout << listNumber[10000] << endl;
return 0;
}
but the output is always change, i don't know why. Can you help me to figure it out?
Thank You.
You never initialize the array. That means its contents will be indeterminate and even reading that contents (like you do in the loop condition) leads to undefined behavior.
You need to initialize the array:
long long listNumber[10001] = {}; // Initialize all elements to zero

Round robin algorithm in a loop

How round-robin algorithm can be implemented that runs in a loop for ever?
for (int i = 0; ;i++){
roundRobinIndex = i % numberOfWorkers;
}
The problems with the way above is that integer overflow problem. It can also be implemented with checking the value of i:
for (int i = 0; ;i++){
roundRobinIndex = i % numberOfWorkers;
if i == maxNumber{
i = 0;
}
}
But this way seems ugly. Maybe there is more elegant way?
Why not ?
int numberOfWorkers = 10
int roundRobinIndex = numberOfWorkers - 1
while(true){
roundRobinIndex = (roundRobinIndex + 1) % numberOfWorkers
}
or with a for-loop
for (int i = 0; ;i = (i + 1) % numberOfWorkers){
roundRobinIndex = i;
}
We can now get rid of i
Avoiding any modulo call, we can do:
constexpr int nextRR(int curIdx, int sz) {
if(curIdx==sz-1) {
return 0;
}
return curIdx+1;
}
for (int rrIndex = 0;;rrIndex = nextRR(rrIndex, sz)) {
// use rrIndex here ...
}
This will be performance-wise more effective than any modulo-based solution, if the number of workers is not known at compile time.
Note that nextRR can also be written like this, to optimize even further for platforms where comparison with 0 is faster than a comparison with a variable:
constexpr int nextRR(int curIdx, int sz) {
if(curIdx==0) {
return sz-1;
}
return curIdx-1;
}
For completeness (I agree that pLopeGG's answer is more elegant) - your way would work perfectly well if you make i an unsigned int rather than int since the overflow is defined in the standard for unsigned overflows, but not signed.
ie
for (unsigned int i = 0; ;i++){
roundRobinIndex = i % numberOfWorkers;
}
Why not put the % into the loop?
for (int i = 0; ;++i, i %= numberOfWorkers)
{
}

How do you find multiplicity of a prime factor in a prime factorization of number?

I have to find multiplicity of smallest prime factor in all numbers till 10^7.I am using Sieve of Eratosthenes to find all the prime numbers. And there in a seperate array phi i am storing smallest prime factors of composite numbers.Here is my code for that
for(ull i=2;i<=m;i++)
{
if (check[i])
{
uncheck[i]=true;
for (ull k=i*i; k<=n; k+=i)
{
if(check[k]==true)
phi[k]=g;
check[k]=false;
}
}
}
Now i am running a loop till n and using a loop inside it to calculate it.
Here is code for that
for(ull i=4;i<=n;i++)
{
if(check[i]==false)
{
ull count=0;
ull l=i;
ull r=phi[i];
while(l%r==0)
{
l=l/r;
count++;
}
cout<<count<<'\n';
}
}
Is there any faster way to compute this?
Absolutely, you can do this without a loop.
c is probably at most 64 bits. It cannot contain any factor other than 1 more than 63 times. So instead of a loop, you write 63 nested if-statements.
For the case j == 2 your compiler may have some intrinsic functions that count trailing zero bits. If that is the case, then you handle that case separately and you need only 40 if's, because 3^41 > 2^64.
If you want to evaluate n such that jn = c, then recast the problem to
n = log(c) / log(j).
If n is an integer then your problem is solved.
Of course you need to consider floating point precision here; n might not be an exact integer, but close to one.
One alternative option, though not necessarily the most efficient, is to write a simple recursive function, such as this, assuming you are dealing with ints:
int recurseSubtract(int c, int j, int count){
if ((c==j)) {
return count + 1;
} else {
c = c-j;
subtract(c, j, count++);
}
}
int count = recurseSubtract(c,j,0);
However, see here for the pros and cons of loops vs. recursion.
Since you asked for the "multiplicity of smallest prime factor" you could easily use the same sieve approach to get multiplicity as you used to get the smallest factor.
for(ull i=2;i<=m;i++)
{
if (check[i])
{
uncheck[i]=true; // WHY??
ull k=i*i;
for (ull q=i; q<maxq; k=(q*=i))
for ( ; k<=n; k+=q)
{
if(check[k]==true)
phi[k]=g; // I copied 'g' from you, but didn't you mean 'i'?
if ( phi[k]==g )
count[k]++;
check[k]=false;
}
}
}
If you want to do a little better than that, the step of phi[k]==g and the some of the redundancy in check[k] access are needed only because q values are processed in forward sequence. It would be faster to work with q in reverse. Since q's are only easily computed in forward sequence and there are fairly few q's per i, the easiest way to process q backward would be to convert the loop over q into a recursive function (compute q on the way in and process it after the recursive call).
I found one simple rule but can not really describe in words. Here is another code calculating primenumbers
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double f_power(double val, int exp);
int main(int argc,char* argv[]) {
int p[2];
int ctr = 0;
int ctr2 = 0;
int it_m = 0;
int it_1 = 0;
int it_2 = 0;
int it_c = 0;
int index = 3;
srand(time(NULL));
double t = clock();
double s = clock();
int prime = 2;
FILE *file;
file = fopen("ly_prime.txt", "w");
//f_power(2.0, 57885161)
for (it_m = 2; it_m <= 2000; it_m++) {
for (it_1 = it_m, ctr2 = 0, it_c = it_m; it_1 >= 2; it_1--) {
for (it_2 = it_1; it_2 >= 2; it_2--) {
if (it_1 * it_2 - it_c == 0) {
p[ctr % 2] = it_c;
if (ctr >= 1 && p[ctr % 2] - p[(ctr - 1) % 2] == 2) {
//prime[0] = (p[ctr % 2] - 1);
prime = (p[ctr % 2] - 1);
fprintf(stdout, "|%d _ i: %d _ %d\n", isPrime(prime),index, prime);
index++;
}
ctr++;
}
}
}
}
t = clock() - t;
fprintf(file, "|%d_ %d_ %d ", prime, index - 2, ctr);
}
double f_power(double val, int exp) {
int i = 0;
double help = val;
for(i = 1; i < exp; i++) {
val *= help;
}
return val;
}
int isPrime(int number)
{
int i = 2;
for(i=2; i < number; i++)
{
int leftOver=(number % i);
if (leftOver==0)
{
return 1;
break;
}
}
return 0;
}
perhaps it helps understanding, best regards

print a series of numbers optimization part 1

lets say you want to make a program that will print the numbers 1-9 over and over again
123456789123456789123456789
i guess the most obvious way to do it would be to use a loop
int number = 1;
while(true)
{
print(number);
number = number + 1;
if(number > 9)
number = 1;
}
before i go any further, is this the best way to do this or is there a more common way of doing this?
Will this do?
while(true)
{
print("123456789");
}
Everyone using the % operator so far seems to be under the impression that ten values are involved. They also overlook the fact that their logic will sometimes generate 0. One way to do what you want is:
int i = 1;
while (true) {
print(i);
i = (i % 9) + 1;
}
The most obvious way would be this:
for (;;)
{
for (int i = 1; i < 10; ++i)
{
print(i);
}
}
Why you'd want to optifuscate it is beyond me. Output is going to so overwhelm the computation that any kind of optimization is irrelevant.
First off, why are you trying to "optimize" this? Are you optimizing for speed? Space? Readability or maintainability?
A "shorter" way to do this would be like so:
for (int i = 1; true; i++)
{
print(i);
i = (i + 1) % 10;
}
All I did was:
Convert the while loop to a for
loop
Convert increment +
conditional to increment + mod
operation.
This really is a case of micro-optimization.
My answer is based off Mike's answer but with further optimization:
for (int i = 1; true; i++)
{
std::cout << ('0' + i);
i = (i + 1) % 10;
}
Printing a number is way more expansive then printing a char and addition.

Identify the digits in a given number.

I'm new to programming, and I'm stuck at a problem. I want my program to identify the separate digits in a given number, like if I input 4692, it should identify the digits and print 4 6 9 2. And yeah, without using arrays.
A perfect recursion problem to tackle if you're new to programming...
4692/1000 = 4
4692%1000 = 692
692/100 = 6
692%100 = 92
92/10 = 9
92%10 = 2
You should get the idea for the loop you should use now, so that it works for any number. :)
Haven't written C code in year, but this should work.
int i = 12345;
while( i > 0 ){
int nextVal = i % 10;
printf( "%d", nextVal );
i = i / 10;
}
Simple and nice
void PrintDigits(const long n)
{
int m = -1;
int i = 1;
while(true)
{
m = (n%(10*i))/i;
i*= 10;
cout << m << endl;
if (0 == n/i)
break;
}
}
Another approach is to have two loops.
1) First loop: Reverse the number.
int j = 0;
while( i ) {
j *= 10;
j += i % 10;
i /= 10;
}
2) Second loop: Print the numbers from right to left.
while( j ) {
std::cout << j % 10 << ' ';
j /= 10;
}
This is assuming you want the digits printed from right to left. I noticed there are several solutions here that do not have this assumption. If not, then just the second loop would suffice.
I think the idea is to have non reapeating digits printed (otherwise it would be too simple)... well, you can keep track of the already printed integers without having an array encoding them in another integer.
some pseudo C, to give you a clue:
int encoding = 0;
int d;
while (keep_looking()) {
d = get_digit();
if (encoding/(2**d)%2 == 0) {
print(d);
encoding += 2**d;
}
}
Here is a simple solution if you want to just print the digits from the number.
#include <stdio.h>
/**
printdigits
*/
void printDigits(int num) {
char buff[128] = "";
sprintf(buff, "%d ", num);
int i = 0;
while (buff[i] != '\0') {
printf("%c ", buff[i]);
i++;
}
printf("\n");
}
/*
main function
*/
int main(int argc, char** argv) {
int digits = 4321;
printDigits(digits);
return 0;
}
Is it correct
int main()
{
int number;
cin>>number;
int nod=0;
int same=number;
while(same){
same/=10;
nod++;
}
while(nod--){
cout<<(int)number/(int)pow10(nod)%10<<"\t";
}
return 0;
}