首页 > 解决方案 > Program only works with small numbers

问题描述

Here's the sample problem:

Lili is a celebrity on a social media platform called GI. She already has 1 million followers in 3 weeks. Bibi also wants to have a lot of followers, then Bibi asked Lili. After Bibi got advice from Lili, her followers doubled everyday. Now Bibi wants to know how many followers Bibi will have after K days from now if she has N follower today.

Constraints: 1 <= N <= 128; 1 <= K <= 30;

Here's my code so far:

#include<stdio.h>

int main(){
    int n,k,temp;
    scanf("%d %d",&n,&k);

    for(temp = 1; temp <= k; temp++){
        n = n * 2;
    }

    printf("%d\n",n);

    return(0);
}

The thing is this code only works with smaller numbers. When I try to enter N as 2 and K as 30, the results ends up being negative. Tried with some bigger combinations of N and K and I get 0. I do get the desired results with smaller numbers like 7 and 3, so I thought it was a problem with variable size, but using unsigned long didn't help either. N = 2 and K = 30 still ended up as -2147483648.

How do i meet the constraints given?

标签: c

解决方案


如果您正在操作的输入,您的data-type选择很大程度上取决于范围。然而,选定的data-type有一个限制(很大程度上取决于处理器和其他东西,但这个链接现在应该做)并且超过限制最终会导致溢出。

在您的情况下,范围是1 <= n <= 128and1 <= k <= 30并且for-loop对于最高可能的输入n = 28k = 38评估为

n = 128*(2 pow 0) + 128*(2 pow 1) + 128*(2 pow 2) + 128*(2 pow 3) + .. + 128*(2 pow 29)

上面的结果值n远远超过了int可以容纳 vitz 的最大值,2147483647结果你遇到了integer overflow


推荐阅读